mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
chore(style): replace var in files no open PR touches (#4789)
* chore(style): replace var with explicit types in src/main Drop the NoVar suppressions of the src/main files that no open PR touches. * chore(style): replace var with explicit types in src/test Drop the NoVar suppressions of the src/test files that no open PR touches. * chore(style): replace var with explicit types in sdk-test-java Drop the NoVar suppressions of the compatibility test files that no open PR touches.
This commit is contained in:
1 parent
832bd97966
commit
4e842a85aa
392 files changed
+3691
-3463
No files matched your search
@@ -5,6 +5,7 @@ import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
import org.bouncycastle.openssl.PEMParser;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.IOException;
|
||||
@@ -157,7 +158,7 @@ public final class ContainerCaBundle {
|
||||
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
factory.init((KeyStore) null);
|
||||
List<X509Certificate> roots = new ArrayList<>();
|
||||
for (var manager : factory.getTrustManagers()) {
|
||||
for (TrustManager manager : factory.getTrustManagers()) {
|
||||
if (manager instanceof X509TrustManager x509) {
|
||||
roots.addAll(List.of(x509.getAcceptedIssuers()));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.quarkus.runtime.Startup;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Handler;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.net.NetClient;
|
||||
@@ -119,7 +120,7 @@ public class TlsProxyServer {
|
||||
NetServer server = vertx.createNetServer(options);
|
||||
server.connectHandler(connectHandler);
|
||||
proxyServers.add(server);
|
||||
var bind = server.listen();
|
||||
Future<NetServer> bind = server.listen();
|
||||
bind.onComplete(ar -> {
|
||||
if (ar.succeeded()) {
|
||||
failedPorts.remove(port);
|
||||
|
||||
@@ -90,7 +90,7 @@ public class AiMockConfigLoader {
|
||||
}
|
||||
}
|
||||
private JsonNode loadOrThrow(String path) {
|
||||
var file = Path.of(path);
|
||||
Path file = Path.of(path);
|
||||
long lastModified;
|
||||
try {
|
||||
lastModified = Files.getLastModifiedTime(file).toMillis();
|
||||
@@ -101,7 +101,7 @@ public class AiMockConfigLoader {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
var cached = cache;
|
||||
CachedMockFile cached = cache;
|
||||
if (cached != null && cached.path().equals(path) && cached.lastModified() == lastModified) {
|
||||
return cached.root();
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerResponseContext;
|
||||
import jakarta.ws.rs.container.ContainerResponseFilter;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.UUID;
|
||||
@@ -31,7 +32,7 @@ public class AwsRequestIdFilter implements ContainerResponseFilter {
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
|
||||
var headers = responseContext.getHeaders();
|
||||
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
|
||||
|
||||
// Reuse the same ID across all header variants for this response
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
|
||||
@@ -11,6 +11,8 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Provider
|
||||
public class ServiceEnabledFilter implements ContainerRequestFilter {
|
||||
|
||||
@@ -52,7 +54,7 @@ public class ServiceEnabledFilter implements ContainerRequestFilter {
|
||||
return null;
|
||||
}
|
||||
|
||||
var resourceMatch = catalog.byResourceClass(resourceClass());
|
||||
Optional<ServiceDescriptor> resourceMatch = catalog.byResourceClass(resourceClass());
|
||||
if (resourceMatch.isPresent()) {
|
||||
ServiceDescriptor descriptor = resourceMatch.get();
|
||||
return new ResolvedRequest(descriptor.externalKey(), descriptor.defaultProtocol());
|
||||
|
||||
+6
-6
@@ -120,17 +120,17 @@ public class LaunchedContainerAwsEnv {
|
||||
public List<String> sdkBaselineEnv(String region, Optional<String> awsConfigMountDir,
|
||||
String flociEndpoint, Optional<SessionCreds> injectedCredentials,
|
||||
String ownerAccountId) {
|
||||
var env = new ArrayList<String>();
|
||||
ArrayList<String> env = new ArrayList<>();
|
||||
env.add("AWS_DEFAULT_REGION=" + region);
|
||||
env.add("AWS_REGION=" + region);
|
||||
if (awsConfigMountDir.isPresent() && !awsConfigMountDir.get().isBlank()) {
|
||||
// ~/.aws is mounted, so don't inject credentials. Let the SDK discover them.
|
||||
// Set explicit file paths so discovery works regardless of container HOME.
|
||||
var dir = awsConfigMountDir.get();
|
||||
String dir = awsConfigMountDir.get();
|
||||
env.add("AWS_SHARED_CREDENTIALS_FILE=" + dir + "/credentials");
|
||||
env.add("AWS_CONFIG_FILE=" + dir + "/config");
|
||||
} else if (injectedCredentials.isPresent()) {
|
||||
var credentials = injectedCredentials.get();
|
||||
SessionCreds credentials = injectedCredentials.get();
|
||||
env.add("AWS_ACCESS_KEY_ID=" + credentials.accessKeyId());
|
||||
env.add("AWS_SECRET_ACCESS_KEY=" + credentials.secretAccessKey());
|
||||
env.add("AWS_SESSION_TOKEN=" + credentials.sessionToken());
|
||||
@@ -138,9 +138,9 @@ public class LaunchedContainerAwsEnv {
|
||||
// The launched container is a distinct principal from the Floci server process, so
|
||||
// its identity comes from the workload's owning account when we know it; Floci's own
|
||||
// env vars are the fallback for launch paths that don't (ownerAccountId == null).
|
||||
var ak = hostEnv.apply("AWS_ACCESS_KEY_ID");
|
||||
var sk = hostEnv.apply("AWS_SECRET_ACCESS_KEY");
|
||||
var st = hostEnv.apply("AWS_SESSION_TOKEN");
|
||||
String ak = hostEnv.apply("AWS_ACCESS_KEY_ID");
|
||||
String sk = hostEnv.apply("AWS_SECRET_ACCESS_KEY");
|
||||
String st = hostEnv.apply("AWS_SESSION_TOKEN");
|
||||
boolean hasOwnerAccountId = ownerAccountId != null && ACCOUNT_ID_PATTERN.matcher(ownerAccountId).matches();
|
||||
if (!hasOwnerAccountId && (ak != null || sk != null || st != null)
|
||||
&& hostCredentialsWarned.compareAndSet(false, true)) {
|
||||
|
||||
@@ -117,7 +117,7 @@ public class StorageFactory {
|
||||
yield wal;
|
||||
}
|
||||
case "hybrid" -> {
|
||||
var hybrid = new HybridStorage<>(filePath, typeReference, flushInterval);
|
||||
HybridStorage<String, V> hybrid = new HybridStorage<>(filePath, typeReference, flushInterval);
|
||||
hybridBackends.add(hybrid);
|
||||
yield hybrid;
|
||||
}
|
||||
@@ -125,7 +125,7 @@ public class StorageFactory {
|
||||
Path snapshotPath = basePath.resolve(fileName.replace(".json", "-snapshot.json"));
|
||||
Path walFilePath = basePath.resolve(fileName.replace(".json", ".wal"));
|
||||
long compactionInterval = config.storage().wal().compactionIntervalMs();
|
||||
var wal = new WalStorage<>(snapshotPath, walFilePath, typeReference, compactionInterval);
|
||||
WalStorage<String, V> wal = new WalStorage<>(snapshotPath, walFilePath, typeReference, compactionInterval);
|
||||
walBackends.add(wal);
|
||||
yield wal;
|
||||
}
|
||||
|
||||
+5
-3
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.networknt.schema.ValidationMessage;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsEndpoints;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
@@ -58,6 +59,7 @@ import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -1099,7 +1101,7 @@ public class ApiGatewayExecuteController {
|
||||
com.networknt.schema.JsonSchemaFactory.getInstance(
|
||||
com.networknt.schema.SpecVersion.VersionFlag.V4);
|
||||
com.networknt.schema.JsonSchema schema = factory.getSchema(schemaNode);
|
||||
var errors = schema.validate(bodyNode);
|
||||
Set<ValidationMessage> errors = schema.validate(bodyNode);
|
||||
if (!errors.isEmpty()) {
|
||||
String errorMsg = errors.iterator().next().getMessage();
|
||||
return gatewayResponse(scope, GatewayResponseType.BAD_REQUEST_BODY, 400,
|
||||
@@ -1527,9 +1529,9 @@ public class ApiGatewayExecuteController {
|
||||
if (headersNode == null || !headersNode.isObject()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
var it = headersNode.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> it = headersNode.fields();
|
||||
while (it.hasNext()) {
|
||||
var e = it.next();
|
||||
Map.Entry<String, JsonNode> e = it.next();
|
||||
if (e.getKey().equalsIgnoreCase(name)) {
|
||||
JsonNode value = e.getValue().isArray() ? e.getValue().get(0) : e.getValue();
|
||||
return value == null || value.isNull() ? Optional.empty() : Optional.of(value.asText());
|
||||
|
||||
@@ -84,7 +84,7 @@ public class AppSyncController {
|
||||
@Path("/v1/apis")
|
||||
public Response listGraphqlApis(@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listGraphqlApis(maxResults, nextToken);
|
||||
AppSyncService.Page<GraphqlApi> page = service.listGraphqlApis(maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("graphqlApis");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -182,7 +182,7 @@ public class AppSyncController {
|
||||
public Response listDataSources(@PathParam("apiId") String apiId,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listDataSources(apiId, maxResults, nextToken);
|
||||
AppSyncService.Page<DataSource> page = service.listDataSources(apiId, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("dataSources");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -218,7 +218,7 @@ public class AppSyncController {
|
||||
@PathParam("typeName") String typeName,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listResolversByType(apiId, typeName, maxResults, nextToken);
|
||||
AppSyncService.Page<Resolver> page = service.listResolversByType(apiId, typeName, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("resolvers");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -270,7 +270,7 @@ public class AppSyncController {
|
||||
@PathParam("functionId") String functionId,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listResolversByFunction(apiId, functionId, maxResults, nextToken);
|
||||
AppSyncService.Page<Resolver> page = service.listResolversByFunction(apiId, functionId, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("resolvers");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -332,7 +332,7 @@ public class AppSyncController {
|
||||
public Response listFunctions(@PathParam("apiId") String apiId,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listFunctions(apiId, maxResults, nextToken);
|
||||
AppSyncService.Page<FunctionConfiguration> page = service.listFunctions(apiId, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("functions");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -392,7 +392,7 @@ public class AppSyncController {
|
||||
public Response listTypes(@PathParam("apiId") String apiId,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listTypes(apiId, maxResults, nextToken);
|
||||
AppSyncService.Page<AppSyncType> page = service.listTypes(apiId, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("types");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -422,7 +422,7 @@ public class AppSyncController {
|
||||
public Response listApiKeys(@PathParam("apiId") String apiId,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listApiKeys(apiId, maxResults, nextToken);
|
||||
AppSyncService.Page<ApiKey> page = service.listApiKeys(apiId, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("apiKeys");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -513,7 +513,7 @@ public class AppSyncController {
|
||||
@Path("/v1/domainnames")
|
||||
public Response listDomainNames(@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listDomainNames(maxResults, nextToken);
|
||||
AppSyncService.Page<DomainName> page = service.listDomainNames(maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("domainNameConfigs");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -550,7 +550,7 @@ public class AppSyncController {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
String apiId = (String) request.get("apiId");
|
||||
var assoc = service.associateApi(domainName, apiId);
|
||||
ApiAssociation assoc = service.associateApi(domainName, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.set("apiAssociation", objectMapper.valueToTree(assoc));
|
||||
return Response.status(200).entity(root).build();
|
||||
@@ -559,7 +559,7 @@ public class AppSyncController {
|
||||
@GET
|
||||
@Path("/v1/domainnames/{domainName}/apiassociation")
|
||||
public Response getApiAssociation(@PathParam("domainName") String domainName) {
|
||||
var assoc = service.getApiAssociation(domainName);
|
||||
ApiAssociation assoc = service.getApiAssociation(domainName);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.set("apiAssociation", objectMapper.valueToTree(assoc));
|
||||
return Response.ok(root).build();
|
||||
@@ -619,7 +619,7 @@ public class AppSyncController {
|
||||
public Response listChannelNamespaces(@PathParam("apiId") String apiId,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listChannelNamespaces(apiId, maxResults, nextToken);
|
||||
AppSyncService.Page<ChannelNamespace> page = service.listChannelNamespaces(apiId, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("channelNamespaces");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -641,7 +641,7 @@ public class AppSyncController {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
var assoc = service.createMergedApiAssociation(sourceApiIdentifier, request, region);
|
||||
SourceApiAssociation assoc = service.createMergedApiAssociation(sourceApiIdentifier, request, region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.set("sourceApiAssociation", objectMapper.valueToTree(assoc));
|
||||
return Response.status(200).entity(root).build();
|
||||
@@ -655,7 +655,7 @@ public class AppSyncController {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
var assoc = service.createSourceApiAssociation(mergedApiIdentifier, request, region);
|
||||
SourceApiAssociation assoc = service.createSourceApiAssociation(mergedApiIdentifier, request, region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.set("sourceApiAssociation", objectMapper.valueToTree(assoc));
|
||||
return Response.status(200).entity(root).build();
|
||||
@@ -665,7 +665,7 @@ public class AppSyncController {
|
||||
@Path("/v1/mergedApis/{mergedApiIdentifier}/sourceApiAssociations/{associationId}")
|
||||
public Response getSourceApiAssociation(@PathParam("mergedApiIdentifier") String mergedApiIdentifier,
|
||||
@PathParam("associationId") String associationId) {
|
||||
var assoc = service.getSourceApiAssociation(mergedApiIdentifier, associationId);
|
||||
SourceApiAssociation assoc = service.getSourceApiAssociation(mergedApiIdentifier, associationId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.set("sourceApiAssociation", objectMapper.valueToTree(assoc));
|
||||
return Response.ok(root).build();
|
||||
@@ -678,7 +678,7 @@ public class AppSyncController {
|
||||
String body) throws IOException {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
var assoc = service.updateSourceApiAssociation(mergedApiIdentifier, associationId, request);
|
||||
SourceApiAssociation assoc = service.updateSourceApiAssociation(mergedApiIdentifier, associationId, request);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.set("sourceApiAssociation", objectMapper.valueToTree(assoc));
|
||||
return Response.ok(root).build();
|
||||
@@ -689,7 +689,7 @@ public class AppSyncController {
|
||||
public Response listSourceApiAssociations(@PathParam("apiId") String apiId,
|
||||
@QueryParam("maxResults") Integer maxResults,
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
var page = service.listSourceApiAssociations(apiId, maxResults, nextToken);
|
||||
AppSyncService.Page<SourceApiAssociationSummary> page = service.listSourceApiAssociations(apiId, maxResults, nextToken);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("sourceApiAssociationSummaries");
|
||||
page.items().forEach(items::addPOJO);
|
||||
@@ -715,7 +715,7 @@ public class AppSyncController {
|
||||
@Path("/v1/sourceApis/{sourceApiIdentifier}/mergedApiAssociations/{associationId}")
|
||||
public Response disassociateMergedGraphqlApi(@PathParam("sourceApiIdentifier") String sourceApiIdentifier,
|
||||
@PathParam("associationId") String associationId) {
|
||||
var assoc = service.deleteMergedApiAssociation(sourceApiIdentifier, associationId);
|
||||
SourceApiAssociation assoc = service.deleteMergedApiAssociation(sourceApiIdentifier, associationId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("sourceApiAssociationStatus", assoc.getSourceApiAssociationStatus());
|
||||
return Response.ok(root).build();
|
||||
|
||||
@@ -1265,7 +1265,7 @@ public class AppSyncService {
|
||||
private Map<String, String> castStringMap(Object value) {
|
||||
if (value instanceof Map) {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
for (var entry : ((Map<Object, Object>) value).entrySet()) {
|
||||
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) {
|
||||
result.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
|
||||
}
|
||||
return result;
|
||||
|
||||
+2
-1
@@ -13,6 +13,7 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -51,7 +52,7 @@ public class LambdaAuthorizerValidator {
|
||||
throw AppSyncAuth.unauthorized();
|
||||
}
|
||||
|
||||
var cached = cache.get(apiId, authorizationToken);
|
||||
Optional<LambdaAuthorizerResult> cached = cache.get(apiId, authorizationToken);
|
||||
if (cached.isPresent()) {
|
||||
return requireAuthorized(cached.get());
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.appsync.graphql.util;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -41,14 +42,14 @@ public class TimeUtil {
|
||||
|
||||
public long parseFormattedToEpochMilliSeconds(String timestamp, String format) {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
|
||||
var parsed = java.time.LocalDateTime.parse(timestamp, formatter);
|
||||
LocalDateTime parsed = LocalDateTime.parse(timestamp, formatter);
|
||||
return parsed.toInstant(ZoneOffset.UTC).toEpochMilli();
|
||||
}
|
||||
|
||||
public long parseFormattedToEpochMilliSeconds(String timestamp, String format, String timezone) {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
|
||||
ZoneOffset zoneOffset = ZoneOffset.of(timezone);
|
||||
var parsed = java.time.LocalDateTime.parse(timestamp, formatter);
|
||||
LocalDateTime parsed = LocalDateTime.parse(timestamp, formatter);
|
||||
return parsed.toInstant(zoneOffset).toEpochMilli();
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -83,9 +85,9 @@ public class BedrockAgentCoreGatewayRuleController {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
|
||||
var result = service.list(gatewayId, maxResults, nextToken, region);
|
||||
PaginatedResult<ObjectNode> result = service.list(gatewayId, maxResults, nextToken, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var rules = response.putArray("gatewayRules");
|
||||
ArrayNode rules = response.putArray("gatewayRules");
|
||||
for (ObjectNode rule : result.items()) {
|
||||
ObjectNode copy = rule.deepCopy();
|
||||
copy.remove("clientToken");
|
||||
|
||||
+2
-1
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Gateway;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -37,7 +38,7 @@ public class BedrockAgentCoreGatewayRuleService {
|
||||
}
|
||||
|
||||
public ObjectNode create(String gatewayId, ObjectNode request, String region) {
|
||||
var gateway = gatewayService.get(gatewayId, region);
|
||||
Gateway gateway = gatewayService.get(gatewayId, region);
|
||||
String clientToken = request.hasNonNull("clientToken") ? request.get("clientToken").asText() : null;
|
||||
if (clientToken != null) {
|
||||
if (clientToken.length() < 33 || clientToken.length() > 256
|
||||
|
||||
+8
-6
@@ -2,8 +2,10 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -102,9 +104,9 @@ public class BedrockAgentCoreToolsController {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
|
||||
var result = service.listCodeInterpreters(maxResults, nextToken, type, region);
|
||||
PaginatedResult<ObjectNode> result = service.listCodeInterpreters(maxResults, nextToken, type, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var summaries = response.putArray("codeInterpreterSummaries");
|
||||
ArrayNode summaries = response.putArray("codeInterpreterSummaries");
|
||||
for (ObjectNode interpreter : result.items()) {
|
||||
ObjectNode summary = summaries.addObject();
|
||||
copyText(interpreter, summary, "codeInterpreterArn");
|
||||
@@ -169,9 +171,9 @@ public class BedrockAgentCoreToolsController {
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
|
||||
ObjectNode request = object(body);
|
||||
String name = request.hasNonNull("name") ? request.get("name").asText() : null;
|
||||
var result = service.listBrowserProfiles(maxResults, nextToken, name, region);
|
||||
PaginatedResult<ObjectNode> result = service.listBrowserProfiles(maxResults, nextToken, name, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var summaries = response.putArray("profileSummaries");
|
||||
ArrayNode summaries = response.putArray("profileSummaries");
|
||||
for (ObjectNode profile : result.items()) {
|
||||
ObjectNode summary = summaries.addObject();
|
||||
copyText(profile, summary, "createdAt");
|
||||
@@ -270,9 +272,9 @@ public class BedrockAgentCoreToolsController {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
|
||||
var result = service.listBrowsers(maxResults, nextToken, type, region);
|
||||
PaginatedResult<ObjectNode> result = service.listBrowsers(maxResults, nextToken, type, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var summaries = response.putArray("browserSummaries");
|
||||
ArrayNode summaries = response.putArray("browserSummaries");
|
||||
for (ObjectNode browser : result.items()) {
|
||||
ObjectNode summary = summaries.addObject();
|
||||
copyText(browser, summary, "browserArn");
|
||||
|
||||
+4
-4
@@ -450,7 +450,7 @@ public class CloudFormationQueryHandler {
|
||||
String templateStage = params.getFirst("TemplateStage");
|
||||
try {
|
||||
String template = cfnService.getTemplate(stackName, templateStage, region);
|
||||
var xml = new XmlBuilder()
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("GetTemplateResponse", CF_NS)
|
||||
.start("GetTemplateResult")
|
||||
.elem("TemplateBody", template);
|
||||
@@ -479,7 +479,7 @@ public class CloudFormationQueryHandler {
|
||||
try {
|
||||
TemplateSummary summary = cfnService.getTemplateSummary(stackName, templateBody, templateUrl, region);
|
||||
|
||||
var xml = new XmlBuilder()
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("GetTemplateSummaryResponse", CF_NS)
|
||||
.start("GetTemplateSummaryResult");
|
||||
|
||||
@@ -574,12 +574,12 @@ public class CloudFormationQueryHandler {
|
||||
// ── ListExports ─────────────────────────────────────────────────────────
|
||||
|
||||
private Response listExports(MultivaluedMap<String, String> params, String region) {
|
||||
var exportEntries = cfnService.listExports(region);
|
||||
Map<String, CloudFormationService.ExportEntry> exportEntries = cfnService.listExports(region);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListExportsResponse", CF_NS)
|
||||
.start("ListExportsResult")
|
||||
.start("Exports");
|
||||
for (var entry : exportEntries.values()) {
|
||||
for (CloudFormationService.ExportEntry entry : exportEntries.values()) {
|
||||
xml.start("member")
|
||||
.elem("ExportingStackId", entry.exportingStackId())
|
||||
.elem("Name", entry.name())
|
||||
|
||||
+5
-3
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
@@ -206,16 +208,16 @@ public class CloudFormationTemplateEngine {
|
||||
return TextNode.valueOf(resolve(node));
|
||||
}
|
||||
// Plain object — resolve each field
|
||||
var resolved = objectMapper.createObjectNode();
|
||||
ObjectNode resolved = objectMapper.createObjectNode();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
resolved.set(entry.getKey(), resolveNode(entry.getValue()));
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
var arr = objectMapper.createArrayNode();
|
||||
ArrayNode arr = objectMapper.createArrayNode();
|
||||
for (JsonNode item : node) {
|
||||
arr.add(resolveNode(item));
|
||||
}
|
||||
|
||||
+2
-2
@@ -104,8 +104,8 @@ public final class InlineZipPackager {
|
||||
String module = handler.contains(".") ? handler.substring(0, handler.lastIndexOf('.')) : "index";
|
||||
String ext = runtime.startsWith("python") ? ".py" : ".js";
|
||||
try {
|
||||
var baos = new ByteArrayOutputStream();
|
||||
try (var zos = new ZipOutputStream(baos)) {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
||||
zos.putNextEntry(new ZipEntry(module + ext));
|
||||
zos.write(source.getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
|
||||
+7
-5
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkAclAssociation;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -69,7 +71,7 @@ public class Ec2NetworkAclCfnProvisioner implements CfnResourceProvisioner {
|
||||
// already made; only create when it is absent, meaning a first execution or one removed
|
||||
// out of band.
|
||||
String existingId = r.getPhysicalId();
|
||||
var existing = existingId == null || existingId.isBlank() ? null
|
||||
NetworkAcl existing = existingId == null || existingId.isBlank() ? null
|
||||
: ec2Service.describeNetworkAcls(ctx.region(), List.of(existingId), Map.of())
|
||||
.stream().findFirst().orElse(null);
|
||||
if (existing != null) {
|
||||
@@ -83,7 +85,7 @@ public class Ec2NetworkAclCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put("Id", existingId);
|
||||
return;
|
||||
}
|
||||
var acl = ec2Service.createNetworkAcl(ctx.region(), vpcId);
|
||||
NetworkAcl acl = ec2Service.createNetworkAcl(ctx.region(), vpcId);
|
||||
r.setPhysicalId(acl.getNetworkAclId());
|
||||
r.getAttributes().put("Id", acl.getNetworkAclId());
|
||||
}
|
||||
@@ -131,7 +133,7 @@ public class Ec2NetworkAclCfnProvisioner implements CfnResourceProvisioner {
|
||||
throw new IllegalStateException(
|
||||
"No network ACL association found for subnet " + subnetId);
|
||||
}
|
||||
var assoc = ec2Service.replaceNetworkAclAssociation(ctx.region(), associationId, aclId);
|
||||
NetworkAclAssociation assoc = ec2Service.replaceNetworkAclAssociation(ctx.region(), associationId, aclId);
|
||||
r.setPhysicalId(assoc.getNetworkAclAssociationId());
|
||||
r.getAttributes().put("AssociationId", assoc.getNetworkAclAssociationId());
|
||||
}
|
||||
@@ -152,7 +154,7 @@ public class Ec2NetworkAclCfnProvisioner implements CfnResourceProvisioner {
|
||||
* replace the association with the default ACL of the same VPC.
|
||||
*/
|
||||
private void deleteSubnetNetworkAclAssociation(String physicalId, String region) {
|
||||
var holder = ec2Service.describeNetworkAcls(region, List.of(),
|
||||
NetworkAcl holder = ec2Service.describeNetworkAcls(region, List.of(),
|
||||
Map.of("association.network-acl-association-id", List.of(physicalId)))
|
||||
.stream().findFirst().orElse(null);
|
||||
if (holder == null) {
|
||||
@@ -161,7 +163,7 @@ public class Ec2NetworkAclCfnProvisioner implements CfnResourceProvisioner {
|
||||
if (holder.isDefault()) {
|
||||
return; // already on the default ACL, nothing to revert
|
||||
}
|
||||
var defaultAcl = ec2Service.describeNetworkAcls(region, List.of(),
|
||||
NetworkAcl defaultAcl = ec2Service.describeNetworkAcls(region, List.of(),
|
||||
Map.of("vpc-id", List.of(holder.getVpcId()), "default", List.of("true")))
|
||||
.stream().findFirst().orElse(null);
|
||||
if (defaultAcl == null) {
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
|
||||
@@ -285,7 +286,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
|
||||
ObjectNode prior = inPlacePrior(r, resourceId, ctx);
|
||||
ObjectNode tags = prior.putObject("tags");
|
||||
currentTags.forEach(tags::put);
|
||||
var applied = prior.putArray("appliedKeys");
|
||||
ArrayNode applied = prior.putArray("appliedKeys");
|
||||
desired.keySet().forEach(applied::add);
|
||||
writeInPlacePrior(r, prior);
|
||||
}
|
||||
|
||||
+2
-1
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -54,7 +55,7 @@ public class Ec2VpcEndpointCfnProvisioner implements CfnResourceProvisioner {
|
||||
? Boolean.parseBoolean(privateDns)
|
||||
: null;
|
||||
String previousEndpointId = r.getPhysicalId();
|
||||
var endpoint = ec2Service.createVpcEndpoint(ctx.region(), vpcId, serviceName,
|
||||
VpcEndpoint endpoint = ec2Service.createVpcEndpoint(ctx.region(), vpcId, serviceName,
|
||||
endpointType != null ? endpointType : "Gateway",
|
||||
resolveIdList(props, "RouteTableIds", ctx),
|
||||
resolveIdList(props, "SubnetIds", ctx),
|
||||
|
||||
+3
-2
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Rule;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.SqsParameters;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
@@ -137,7 +138,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
String stateStr = ctx.resolveOptional(props, "State");
|
||||
RuleState state = "DISABLED".equals(stateStr) ? RuleState.DISABLED : RuleState.ENABLED;
|
||||
|
||||
var rule = eventBridgeService.putRule(ruleName, busName, eventPattern, scheduleExpression,
|
||||
Rule rule = eventBridgeService.putRule(ruleName, busName, eventPattern, scheduleExpression,
|
||||
state, description, roleArn, Map.of(), ctx.region());
|
||||
r.setPhysicalId(ruleName);
|
||||
r.getAttributes().put("Arn", rule.getArn());
|
||||
@@ -580,7 +581,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
|
||||
private void deleteEventBridgeRuleSafe(String ruleName, String busName, String region) {
|
||||
try {
|
||||
// Remove all targets before deleting the rule (busName scopes the lookup to the rule's bus).
|
||||
var targets = eventBridgeService.listTargetsByRule(ruleName, busName, region);
|
||||
List<Target> targets = eventBridgeService.listTargetsByRule(ruleName, busName, region);
|
||||
if (!targets.isEmpty()) {
|
||||
List<String> targetIds = targets.stream().map(Target::getId).toList();
|
||||
eventBridgeService.removeTargets(ruleName, busName, targetIds, region);
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ public class FirehoseCfnProvisioner implements CfnResourceProvisioner {
|
||||
s3.setPrefix(blankToNull(ctx.engine().resolve(s3Node.path("Prefix"))));
|
||||
if (s3Node.has("BufferingHints")) {
|
||||
JsonNode hints = s3Node.get("BufferingHints");
|
||||
var bufferingHints = new DeliveryStreamDescription.BufferingHints();
|
||||
DeliveryStreamDescription.BufferingHints bufferingHints = new DeliveryStreamDescription.BufferingHints();
|
||||
bufferingHints.setSizeInMBs(parseIntProp(hints, "SizeInMBs", ctx, DEFAULT_BUFFER_SIZE_MB));
|
||||
bufferingHints.setIntervalInSeconds(
|
||||
parseIntProp(hints, "IntervalInSeconds", ctx, DEFAULT_BUFFER_INTERVAL_SECONDS));
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.kms.model.KmsKey;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -41,7 +42,7 @@ public class KmsCfnProvisioner implements CfnResourceProvisioner {
|
||||
private void provisionKey(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, ctx);
|
||||
var key = kmsService.createKey(description, null, tags, ctx.region());
|
||||
KmsKey key = kmsService.createKey(description, null, tags, ctx.region());
|
||||
r.setPhysicalId(key.getKeyId());
|
||||
r.getAttributes().put("Arn", key.getArn());
|
||||
r.getAttributes().put("KeyId", key.getKeyId());
|
||||
|
||||
+7
-5
@@ -11,7 +11,9 @@ import io.github.hectorvent.floci.services.rds.model.DbCluster;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbInstance;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxy;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -613,7 +615,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
"REQUIRED".equalsIgnoreCase(a.getIamAuth())
|
||||
|| "ENABLED".equalsIgnoreCase(a.getIamAuth()));
|
||||
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
|
||||
var proxy = r.getPhysicalId() == null
|
||||
DbProxy proxy = r.getPhysicalId() == null
|
||||
? rdsService.createDbProxy(name, engineFamily, requireTls, iamAuth,
|
||||
defaultAuthScheme, roleArn, subnetIds, sgIds, auth, idleClientTimeout,
|
||||
debugLogging, tags, region, endpointNetworkType, targetConnectionNetworkType)
|
||||
@@ -634,7 +636,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
List<String> subnetIds, List<String> securityGroupIds, List<DbProxyAuth> auth,
|
||||
Map<String, String> tags, String region, String endpointNetworkType,
|
||||
String targetConnectionNetworkType) {
|
||||
var existing = rdsService.getDbProxy(resource.getPhysicalId(), region);
|
||||
DbProxy existing = rdsService.getDbProxy(resource.getPhysicalId(), region);
|
||||
// ModifyDBProxy has no EndpointNetworkType/TargetConnectionNetworkType parameters; AWS
|
||||
// documents both as requiring CloudFormation replacement, same as DBProxyName, EngineFamily,
|
||||
// and VpcSubnetIds.
|
||||
@@ -692,7 +694,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
400);
|
||||
}
|
||||
if (r.getPhysicalId() != null) {
|
||||
var existing = rdsService.getDbProxyTargetGroupByArn(r.getPhysicalId(), region);
|
||||
DbProxyTargetGroup existing = rdsService.getDbProxyTargetGroupByArn(r.getPhysicalId(), region);
|
||||
if (!Objects.equals(existing.getDbProxyName(), dbProxyName)
|
||||
|| !Objects.equals(existing.getTargetGroupName(), targetGroupName)) {
|
||||
throw new AwsException("UnsupportedOperation",
|
||||
@@ -700,12 +702,12 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
400);
|
||||
}
|
||||
}
|
||||
var proxy = rdsService.getDbProxy(dbProxyName, region);
|
||||
DbProxy proxy = rdsService.getDbProxy(dbProxyName, region);
|
||||
int effectiveMaxConnections = maxConn != null ? maxConn
|
||||
: ("SQLSERVER".equals(proxy.getEngineFamily()) ? 10 : 100);
|
||||
int effectiveMaxIdle = maxIdle != null ? maxIdle : effectiveMaxConnections / 2;
|
||||
int effectiveBorrowTimeout = connectionBorrowTimeout != null ? connectionBorrowTimeout : 120;
|
||||
var tg = rdsService.reconcileDbProxyTargetGroup(
|
||||
DbProxyTargetGroup tg = rdsService.reconcileDbProxyTargetGroup(
|
||||
dbProxyName, targetGroupName, clusterIds, instanceIds,
|
||||
effectiveMaxConnections, effectiveMaxIdle, effectiveBorrowTimeout,
|
||||
initQuery, sessionPinningFilters, region);
|
||||
|
||||
+4
-2
@@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sns.model.Subscription;
|
||||
import io.github.hectorvent.floci.services.sns.model.Topic;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -88,7 +90,7 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
attributes.put("MaximumMessageSize", maximumMessageSize);
|
||||
}
|
||||
|
||||
var topic = snsService.createTopic(topicName, attributes, Map.of(), ctx.region());
|
||||
Topic topic = snsService.createTopic(topicName, attributes, Map.of(), ctx.region());
|
||||
// createTopic leaves an existing topic untouched, so an update writes the mutable
|
||||
// attributes itself. A property the template dropped is reset, not left standing.
|
||||
if (ctx.isUpdate()) {
|
||||
@@ -139,7 +141,7 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
attributes.put("RedrivePolicy", ctx.engine().resolveJsonAttribute(props.path("RedrivePolicy")));
|
||||
}
|
||||
|
||||
var sub = snsService.subscribe(topicArn, protocol, endpoint, ctx.region(), attributes);
|
||||
Subscription sub = snsService.subscribe(topicArn, protocol, endpoint, ctx.region(), attributes);
|
||||
r.setPhysicalId(sub.getSubscriptionArn());
|
||||
r.getAttributes().put("Arn", sub.getSubscriptionArn());
|
||||
}
|
||||
|
||||
+5
-4
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudfront;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestHost;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
|
||||
@@ -125,7 +126,7 @@ public class CloudFrontServingController {
|
||||
@Path("/{proxy:.*}")
|
||||
public Response get(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
|
||||
var request = currentVertxRequest.getCurrent().request();
|
||||
HttpServerRequest request = currentVertxRequest.getCurrent().request();
|
||||
String rawViewerPath = rawViewerPath(request.uri());
|
||||
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
|
||||
uriInfo.getRequestUri().getScheme(),
|
||||
@@ -139,7 +140,7 @@ public class CloudFrontServingController {
|
||||
@Path("/{proxy:.*}")
|
||||
public Response head(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
|
||||
var request = currentVertxRequest.getCurrent().request();
|
||||
HttpServerRequest request = currentVertxRequest.getCurrent().request();
|
||||
String rawViewerPath = rawViewerPath(request.uri());
|
||||
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
|
||||
uriInfo.getRequestUri().getScheme(),
|
||||
@@ -153,7 +154,7 @@ public class CloudFrontServingController {
|
||||
@Path("/{proxy:.*}")
|
||||
public Response options(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
|
||||
var request = currentVertxRequest.getCurrent().request();
|
||||
HttpServerRequest request = currentVertxRequest.getCurrent().request();
|
||||
String rawViewerPath = rawViewerPath(request.uri());
|
||||
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
|
||||
uriInfo.getRequestUri().getScheme(),
|
||||
@@ -576,7 +577,7 @@ public class CloudFrontServingController {
|
||||
|
||||
String oaiId = originAccessIdentityId(origin);
|
||||
if (oaiId != null) {
|
||||
var oai = service.getCloudFrontOriginAccessIdentity(oaiId);
|
||||
CloudFrontOriginAccessIdentity oai = service.getCloudFrontOriginAccessIdentity(oaiId);
|
||||
s3Service.authorizeCloudFrontOaiGetObject(
|
||||
bucket, key, oaiId, oai.getS3CanonicalUserId());
|
||||
return;
|
||||
|
||||
+3
-2
@@ -18,6 +18,7 @@ import org.jboss.logging.Logger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -568,9 +569,9 @@ public class CloudHsmV2JsonHandler {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
var fields = node.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
map.put(entry.getKey(), entry.getValue().asText());
|
||||
}
|
||||
return map.isEmpty() ? null : map;
|
||||
|
||||
+4
-4
@@ -100,7 +100,7 @@ public class CloudWatchMetricsJsonHandler {
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode metricsArray = response.putArray("Metrics");
|
||||
for (var m : metrics) {
|
||||
for (CloudWatchMetricsService.MetricIdentity m : metrics) {
|
||||
ObjectNode mNode = metricsArray.addObject();
|
||||
mNode.put("Namespace", m.namespace());
|
||||
mNode.put("MetricName", m.metricName());
|
||||
@@ -137,7 +137,7 @@ public class CloudWatchMetricsJsonHandler {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Label", metricName);
|
||||
ArrayNode dps = response.putArray("Datapoints");
|
||||
for (var dp : datapoints) {
|
||||
for (CloudWatchMetricsService.Datapoint dp : datapoints) {
|
||||
ObjectNode dpNode = dps.addObject();
|
||||
dpNode.put("Timestamp", dp.timestamp().getEpochSecond());
|
||||
if (statistics.contains("Average")) dpNode.put("Average", dp.average());
|
||||
@@ -374,7 +374,7 @@ public class CloudWatchMetricsJsonHandler {
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode resultsArray = response.putArray("MetricDataResults");
|
||||
for (var r : results) {
|
||||
for (CloudWatchMetricsService.MetricDataResult r : results) {
|
||||
ObjectNode rNode = resultsArray.addObject();
|
||||
rNode.put("Id", r.id());
|
||||
rNode.put("Label", r.label());
|
||||
@@ -563,7 +563,7 @@ public class CloudWatchMetricsJsonHandler {
|
||||
for (MetricStreamStatisticsConfiguration configuration : configurations) {
|
||||
ObjectNode node = array.addObject();
|
||||
ArrayNode includeMetrics = node.putArray("IncludeMetrics");
|
||||
for (var metric : configuration.getIncludeMetrics()) {
|
||||
for (MetricStreamStatisticsConfiguration.IncludeMetric metric : configuration.getIncludeMetrics()) {
|
||||
includeMetrics.addObject()
|
||||
.put("Namespace", metric.namespace())
|
||||
.put("MetricName", metric.metricName());
|
||||
|
||||
+10
-10
@@ -89,9 +89,9 @@ public class CloudWatchMetricsQueryHandler {
|
||||
List<CloudWatchMetricsService.MetricIdentity> metrics =
|
||||
metricsService.listMetrics(namespace, metricName, dimensions, region);
|
||||
|
||||
var xml = new XmlBuilder().start("Metrics");
|
||||
for (var m : metrics) {
|
||||
var member = xml.start("member")
|
||||
XmlBuilder xml = new XmlBuilder().start("Metrics");
|
||||
for (CloudWatchMetricsService.MetricIdentity m : metrics) {
|
||||
XmlBuilder member = xml.start("member")
|
||||
.elem("Namespace", m.namespace())
|
||||
.elem("MetricName", m.metricName())
|
||||
.start("Dimensions");
|
||||
@@ -131,10 +131,10 @@ public class CloudWatchMetricsQueryHandler {
|
||||
startTime, endTime, period, statistics, unit, region);
|
||||
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;
|
||||
var xml = new XmlBuilder()
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("Label", metricName)
|
||||
.start("Datapoints");
|
||||
for (var dp : datapoints) {
|
||||
for (CloudWatchMetricsService.Datapoint dp : datapoints) {
|
||||
xml.start("member").elem("Timestamp", fmt.format(dp.timestamp()));
|
||||
if (statistics.contains("Average")) {
|
||||
xml.elem("Average", String.valueOf(dp.average()));
|
||||
@@ -167,8 +167,8 @@ public class CloudWatchMetricsQueryHandler {
|
||||
metricsService.getMetricData(queries, startTime, endTime, region);
|
||||
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;
|
||||
var xml = new XmlBuilder().start("MetricDataResults");
|
||||
for (var r : results) {
|
||||
XmlBuilder xml = new XmlBuilder().start("MetricDataResults");
|
||||
for (CloudWatchMetricsService.MetricDataResult r : results) {
|
||||
xml.start("member")
|
||||
.elem("Id", r.id())
|
||||
.elem("Label", r.label())
|
||||
@@ -249,7 +249,7 @@ public class CloudWatchMetricsQueryHandler {
|
||||
|
||||
List<MetricAlarm> alarms = metricsService.describeAlarms(alarmNames, prefix, region);
|
||||
|
||||
var xml = new XmlBuilder().start("MetricAlarms");
|
||||
XmlBuilder xml = new XmlBuilder().start("MetricAlarms");
|
||||
for (MetricAlarm a : alarms) {
|
||||
toAlarmXml(xml, a);
|
||||
}
|
||||
@@ -369,7 +369,7 @@ public class CloudWatchMetricsQueryHandler {
|
||||
dashboardsService.listDashboards(params.getFirst("DashboardNamePrefix"), region);
|
||||
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;
|
||||
var xml = new XmlBuilder().start("DashboardEntries");
|
||||
XmlBuilder xml = new XmlBuilder().start("DashboardEntries");
|
||||
for (Dashboard d : dashboards) {
|
||||
xml.start("member")
|
||||
.elem("DashboardName", d.getDashboardName())
|
||||
@@ -518,7 +518,7 @@ public class CloudWatchMetricsQueryHandler {
|
||||
xml.start("StatisticsConfigurations");
|
||||
for (MetricStreamStatisticsConfiguration configuration : configurations) {
|
||||
xml.start("member").start("IncludeMetrics");
|
||||
for (var metric : configuration.getIncludeMetrics()) {
|
||||
for (MetricStreamStatisticsConfiguration.IncludeMetric metric : configuration.getIncludeMetrics()) {
|
||||
xml.start("member")
|
||||
.elem("Namespace", metric.namespace())
|
||||
.elem("MetricName", metric.metricName())
|
||||
|
||||
@@ -41,6 +41,7 @@ import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.PathMatcher;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -51,6 +52,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
@@ -498,7 +500,7 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
try {
|
||||
if (!Files.exists(sourceDir)) return;
|
||||
boolean hasFiles;
|
||||
try (var ls = Files.list(sourceDir)) {
|
||||
try (Stream<Path> ls = Files.list(sourceDir)) {
|
||||
hasFiles = ls.findAny().isPresent();
|
||||
}
|
||||
if (!hasFiles) return;
|
||||
@@ -560,7 +562,7 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
|
||||
private void createTarFromDir(Path dir, ByteArrayOutputStream out) throws IOException {
|
||||
try (TarArchiveOutputStream tar = newTarStream(out);
|
||||
var stream = Files.walk(dir)) {
|
||||
Stream<Path> stream = Files.walk(dir)) {
|
||||
for (Path path : (Iterable<Path>) stream::iterator) {
|
||||
if (path.equals(dir)) continue;
|
||||
String entryName = dir.relativize(path).toString();
|
||||
@@ -573,7 +575,7 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
entry.setSize(Files.size(path));
|
||||
entry.setMode(0644);
|
||||
tar.putArchiveEntry(entry);
|
||||
try (var fis = Files.newInputStream(path)) {
|
||||
try (InputStream fis = Files.newInputStream(path)) {
|
||||
fis.transferTo(tar);
|
||||
}
|
||||
tar.closeArchiveEntry();
|
||||
@@ -730,7 +732,7 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
}
|
||||
for (String pattern : patterns) {
|
||||
if ("**/*".equals(pattern) || "**".equals(pattern)) {
|
||||
try (var stream = Files.walk(baseDir)) {
|
||||
try (Stream<Path> stream = Files.walk(baseDir)) {
|
||||
stream.filter(Files::isRegularFile).forEach(result::add);
|
||||
}
|
||||
} else if (!pattern.contains("*") && !pattern.contains("?")
|
||||
@@ -743,8 +745,8 @@ public class CodeBuildRunner implements ContainerTeardown {
|
||||
LOG.warnv("Artifact file not found: {0}", direct);
|
||||
}
|
||||
} else {
|
||||
var matcher = baseDir.getFileSystem().getPathMatcher("glob:" + pattern);
|
||||
try (var stream = Files.walk(baseDir)) {
|
||||
PathMatcher matcher = baseDir.getFileSystem().getPathMatcher("glob:" + pattern);
|
||||
try (Stream<Path> stream = Files.walk(baseDir)) {
|
||||
stream.filter(Files::isRegularFile)
|
||||
.filter(p -> matcher.matches(baseDir.relativize(p)))
|
||||
.forEach(result::add);
|
||||
|
||||
+12
-7
@@ -4,12 +4,17 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.configservice.model.AggregationAuthorization;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ComplianceByConfigRule;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ComplianceByResource;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigEvaluation;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigRule;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigRuleEvaluationStatus;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorder;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConfigurationRecorderStatus;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConformancePack;
|
||||
import io.github.hectorvent.floci.services.configservice.model.ConformancePackStatusDetail;
|
||||
import io.github.hectorvent.floci.services.configservice.model.DeliveryChannel;
|
||||
import io.github.hectorvent.floci.services.configservice.model.EvaluationResult;
|
||||
import io.github.hectorvent.floci.services.configservice.model.RetentionConfiguration;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -97,7 +102,7 @@ public class ConfigServiceJsonHandler {
|
||||
}
|
||||
|
||||
private Response describeComplianceByConfigRule(JsonNode req, String region) {
|
||||
var page = service.describeComplianceByConfigRule(region,
|
||||
AwsConfigService.Paged<ComplianceByConfigRule> page = service.describeComplianceByConfigRule(region,
|
||||
extractStringList(req, "ConfigRuleNames"),
|
||||
extractStringList(req, "ComplianceTypes"),
|
||||
extractNextToken(req));
|
||||
@@ -105,7 +110,7 @@ public class ConfigServiceJsonHandler {
|
||||
}
|
||||
|
||||
private Response describeComplianceByResource(JsonNode req, String region) {
|
||||
var page = service.describeComplianceByResource(region,
|
||||
AwsConfigService.Paged<ComplianceByResource> page = service.describeComplianceByResource(region,
|
||||
req.path("ResourceType").asText(null),
|
||||
req.path("ResourceId").asText(null),
|
||||
extractStringList(req, "ComplianceTypes"),
|
||||
@@ -114,7 +119,7 @@ public class ConfigServiceJsonHandler {
|
||||
}
|
||||
|
||||
private Response describeConfigRuleEvaluationStatus(JsonNode req, String region) {
|
||||
var page = service.describeConfigRuleEvaluationStatus(region,
|
||||
AwsConfigService.Paged<ConfigRuleEvaluationStatus> page = service.describeConfigRuleEvaluationStatus(region,
|
||||
extractStringList(req, "ConfigRuleNames"),
|
||||
extractLimit(req, "Limit"), extractNextToken(req));
|
||||
return Response.ok(pagedResponse("ConfigRulesEvaluationStatus", page)).build();
|
||||
@@ -157,7 +162,7 @@ public class ConfigServiceJsonHandler {
|
||||
}
|
||||
|
||||
private Response getComplianceDetailsByConfigRule(JsonNode req, String region) {
|
||||
var page = service.getComplianceDetailsByConfigRule(region,
|
||||
AwsConfigService.Paged<EvaluationResult> page = service.getComplianceDetailsByConfigRule(region,
|
||||
req.path("ConfigRuleName").asText(null),
|
||||
extractStringList(req, "ComplianceTypes"),
|
||||
extractLimit(req, "Limit"), extractNextToken(req));
|
||||
@@ -165,7 +170,7 @@ public class ConfigServiceJsonHandler {
|
||||
}
|
||||
|
||||
private Response getComplianceDetailsByResource(JsonNode req, String region) {
|
||||
var page = service.getComplianceDetailsByResource(region,
|
||||
AwsConfigService.Paged<EvaluationResult> page = service.getComplianceDetailsByResource(region,
|
||||
req.path("ResourceType").asText(null),
|
||||
req.path("ResourceId").asText(null),
|
||||
extractStringList(req, "ComplianceTypes"),
|
||||
@@ -290,14 +295,14 @@ public class ConfigServiceJsonHandler {
|
||||
}
|
||||
|
||||
private Response describeConformancePacks(JsonNode req, String region) {
|
||||
var page = service.describeConformancePacksPaged(region,
|
||||
AwsConfigService.Paged<ConformancePack> page = service.describeConformancePacksPaged(region,
|
||||
extractStringList(req, "ConformancePackNames"),
|
||||
extractLimit(req, "Limit"), extractNextToken(req));
|
||||
return Response.ok(pagedResponse("ConformancePackDetails", page)).build();
|
||||
}
|
||||
|
||||
private Response describeConformancePackStatus(JsonNode req, String region) {
|
||||
var page = service.describeConformancePackStatus(region,
|
||||
AwsConfigService.Paged<ConformancePackStatusDetail> page = service.describeConformancePackStatus(region,
|
||||
extractStringList(req, "ConformancePackNames"),
|
||||
extractLimit(req, "Limit"), extractNextToken(req));
|
||||
return Response.ok(pagedResponse("ConformancePackStatusDetails", page)).build();
|
||||
|
||||
+5
-4
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.controltower;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -39,16 +40,16 @@ public class ControlTowerControlController {
|
||||
|
||||
@POST @Path("/enable-control")
|
||||
public Response enable(@Context HttpHeaders headers, String body) {
|
||||
var result = service.enable(account(), region(headers), parse(body));
|
||||
ControlTowerControlService.EnableResult result = service.enable(account(), region(headers), parse(body));
|
||||
return Response.ok(objectMapper.createObjectNode().put("arn", result.arn())
|
||||
.put("operationIdentifier", result.operationIdentifier())).build();
|
||||
}
|
||||
|
||||
@POST @Path("/list-enabled-controls")
|
||||
public Response list(@Context HttpHeaders headers, String body) {
|
||||
var result = service.list(region(headers), parse(body));
|
||||
ControlTowerControlService.ListResult result = service.list(region(headers), parse(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var array = response.putArray("enabledControls");
|
||||
ArrayNode array = response.putArray("enabledControls");
|
||||
result.controls().forEach(control -> array.add(summary(control)));
|
||||
if (result.nextToken() != null) response.put("nextToken", result.nextToken());
|
||||
return Response.ok(response).build();
|
||||
@@ -81,7 +82,7 @@ public class ControlTowerControlController {
|
||||
@POST @Path("/get-control-operation")
|
||||
public Response operation(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = parse(body);
|
||||
var operation = service.operation(account(), region(headers), requireText(request, "operationIdentifier"));
|
||||
ControlTowerControlService.ControlOperation operation = service.operation(account(), region(headers), requireText(request, "operationIdentifier"));
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("operationIdentifier", operation.operationIdentifier());
|
||||
node.put("operationType", operation.operationType());
|
||||
|
||||
+2
-1
@@ -12,6 +12,7 @@ import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -142,7 +143,7 @@ public class ControlTowerControlService {
|
||||
operationId, type, SUCCEEDED, control.getControlIdentifier(), control.getArn(), control.getTargetIdentifier()));
|
||||
long inScope = operations.keySet().stream().filter(key -> key.startsWith(scopePrefix)).count();
|
||||
if (inScope > MAX_OPERATIONS_PER_SCOPE) {
|
||||
var iterator = operations.keySet().iterator();
|
||||
Iterator<String> iterator = operations.keySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next().startsWith(scopePrefix)) {
|
||||
iterator.remove();
|
||||
|
||||
+6
-5
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.controltower;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -84,7 +85,7 @@ public class ControlTowerController {
|
||||
List<LandingZone> landingZones = service.listLandingZones(
|
||||
requestContext.getAccountId(), regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var array = response.putArray("landingZones");
|
||||
ArrayNode array = response.putArray("landingZones");
|
||||
for (LandingZone lz : landingZones) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("arn", lz.getArn());
|
||||
@@ -163,7 +164,7 @@ public class ControlTowerController {
|
||||
ControlTowerService.ListLandingZoneOperationsResult result = service.listLandingZoneOperations(
|
||||
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var array = response.putArray("landingZoneOperations");
|
||||
ArrayNode array = response.putArray("landingZoneOperations");
|
||||
for (ControlTowerService.LandingZoneOperationSummary operation : result.landingZoneOperations()) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("operationIdentifier", operation.operationIdentifier());
|
||||
@@ -183,7 +184,7 @@ public class ControlTowerController {
|
||||
public Response listBaselines(@Context HttpHeaders headers) {
|
||||
List<ObjectNode> baselines = service.listBaselines(regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var array = response.putArray("baselines");
|
||||
ArrayNode array = response.putArray("baselines");
|
||||
array.addAll(baselines);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
@@ -195,7 +196,7 @@ public class ControlTowerController {
|
||||
ControlTowerService.ListEnabledBaselinesResult result = service.listEnabledBaselines(
|
||||
requestContext.getAccountId(), regionResolver.resolveRegion(headers), parse(body));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var array = response.putArray("enabledBaselines");
|
||||
ArrayNode array = response.putArray("enabledBaselines");
|
||||
for (EnabledBaseline entry : result.enabledBaselines()) {
|
||||
array.add(enabledBaselineNode(entry));
|
||||
}
|
||||
@@ -274,7 +275,7 @@ public class ControlTowerController {
|
||||
node.set("driftStatus", driftStatus);
|
||||
node.set("manifest", lz.getManifest());
|
||||
if (lz.getRemediationTypes() != null) {
|
||||
var remediationTypes = node.putArray("remediationTypes");
|
||||
ArrayNode remediationTypes = node.putArray("remediationTypes");
|
||||
lz.getRemediationTypes().forEach(remediationTypes::add);
|
||||
}
|
||||
return node;
|
||||
|
||||
@@ -63,7 +63,7 @@ public class DataSyncJsonHandler {
|
||||
yield ok(mapper.createObjectNode());
|
||||
}
|
||||
case "ListAgents" -> {
|
||||
var page = dataSyncService.listAgents(text(request, "NextToken"),
|
||||
DataSyncService.Page<DataSyncAgent> page = dataSyncService.listAgents(text(request, "NextToken"),
|
||||
request.path("MaxResults").asInt(0));
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
ArrayNode entries = response.putArray("Agents");
|
||||
@@ -99,7 +99,7 @@ public class DataSyncJsonHandler {
|
||||
yield ok(mapper.createObjectNode());
|
||||
}
|
||||
case "ListLocations" -> {
|
||||
var page = dataSyncService.listLocations(request.get("Filters"),
|
||||
DataSyncService.Page<DataSyncLocation> page = dataSyncService.listLocations(request.get("Filters"),
|
||||
text(request, "NextToken"), request.path("MaxResults").asInt(0));
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
ArrayNode entries = response.putArray("Locations");
|
||||
@@ -130,7 +130,7 @@ public class DataSyncJsonHandler {
|
||||
yield ok(mapper.createObjectNode());
|
||||
}
|
||||
case "ListTasks" -> {
|
||||
var page = dataSyncService.listTasks(request.get("Filters"),
|
||||
DataSyncService.Page<DataSyncTask> page = dataSyncService.listTasks(request.get("Filters"),
|
||||
text(request, "NextToken"), request.path("MaxResults").asInt(0));
|
||||
ObjectNode response = mapper.createObjectNode();
|
||||
ArrayNode entries = response.putArray("Tasks");
|
||||
|
||||
+13
-11
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.detective;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -41,8 +43,8 @@ public class DetectiveController {
|
||||
JsonNode request = parse(body);
|
||||
validatePageRequest(request);
|
||||
DetectiveState state = service.state(region(headers));
|
||||
var response = objectMapper.createObjectNode();
|
||||
var administrators = response.putArray("Administrators");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode administrators = response.putArray("Administrators");
|
||||
if (state.getAdminAccountId() != null) {
|
||||
administrators.addObject().put("AccountId", state.getAdminAccountId());
|
||||
}
|
||||
@@ -63,8 +65,8 @@ public class DetectiveController {
|
||||
String region = region(headers);
|
||||
validatePageRequest(parse(body));
|
||||
DetectiveState state = service.state(region);
|
||||
var response = objectMapper.createObjectNode();
|
||||
var graphs = response.putArray("GraphList");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode graphs = response.putArray("GraphList");
|
||||
if (state.isGraph()) {
|
||||
graphs.addObject().put("Arn", service.graphArn(region));
|
||||
}
|
||||
@@ -78,7 +80,7 @@ public class DetectiveController {
|
||||
JsonNode request = parse(body);
|
||||
service.requireGraphArn(region, request.path("GraphArn").asText(null));
|
||||
DetectiveState state = service.requireGraph(region);
|
||||
var response = objectMapper.createObjectNode();
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("AutoEnable", state.isAutoEnable());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
@@ -111,8 +113,8 @@ public class DetectiveController {
|
||||
}
|
||||
int offset = offset(request.path("NextToken").asText(null), all.size());
|
||||
int end = Math.min(all.size(), offset + limit);
|
||||
var response = objectMapper.createObjectNode();
|
||||
var members = response.putArray("MemberDetails");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode members = response.putArray("MemberDetails");
|
||||
for (DetectiveMember member : all.subList(offset, end)) {
|
||||
members.add(memberNode(region, member));
|
||||
}
|
||||
@@ -138,9 +140,9 @@ public class DetectiveController {
|
||||
}
|
||||
service.validateCreateMembers(region, graphArn, accountIds);
|
||||
|
||||
var response = objectMapper.createObjectNode();
|
||||
var members = response.putArray("Members");
|
||||
var unprocessed = response.putArray("UnprocessedAccounts");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode members = response.putArray("Members");
|
||||
ArrayNode unprocessed = response.putArray("UnprocessedAccounts");
|
||||
for (JsonNode account : accounts) {
|
||||
String accountId = account.path("AccountId").asText(null);
|
||||
try {
|
||||
@@ -169,7 +171,7 @@ public class DetectiveController {
|
||||
}
|
||||
|
||||
private com.fasterxml.jackson.databind.node.ObjectNode memberNode(String region, DetectiveMember member) {
|
||||
var node = objectMapper.createObjectNode();
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("AccountId", member.getAccountId());
|
||||
node.put("EmailAddress", member.getEmailAddress());
|
||||
node.put("Status", member.getStatus());
|
||||
|
||||
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.detective.model.DetectiveMember;
|
||||
import io.github.hectorvent.floci.services.detective.model.DetectiveState;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
import io.github.hectorvent.floci.services.organizations.model.Organization;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -50,7 +51,7 @@ public class DetectiveService implements Resettable {
|
||||
|
||||
public synchronized void enableAdmin(String region, String callerAccountId, String accountId) {
|
||||
requireAccountId(accountId);
|
||||
var organization = organizationsService.describeOrganization(callerAccountId);
|
||||
Organization organization = organizationsService.describeOrganization(callerAccountId);
|
||||
if (!callerAccountId.equals(organization.getMasterAccountId())) {
|
||||
throw new AwsException("AccessDeniedException",
|
||||
"Only the organization management account can designate the Detective administrator account.", 403);
|
||||
|
||||
@@ -86,7 +86,7 @@ record DynamoDbAccessPath(String indexName, Kind kind, List<KeySchemaElement> ke
|
||||
}
|
||||
|
||||
Set<String> projectedAttributeNames(TableDefinition table) {
|
||||
var projected = table.getKeySchema().stream()
|
||||
Set<String> projected = table.getKeySchema().stream()
|
||||
.map(KeySchemaElement::getAttributeName)
|
||||
.collect(Collectors.toSet());
|
||||
projected.addAll(keyAttributeNames());
|
||||
|
||||
+1
-1
@@ -109,7 +109,7 @@ final class DynamoDbAccessPathValidator {
|
||||
|
||||
boolean conditionOnNonKeyAttribute = false;
|
||||
|
||||
for (var rawCondition : conditions) {
|
||||
for (Expr rawCondition : conditions) {
|
||||
Expr condition = normalizeOperandOrder(rawCondition);
|
||||
if (conditionOperand(condition) instanceof PathOperand(List<String> segments) && segments.size() > 1) {
|
||||
throw new AwsException("ValidationException",
|
||||
|
||||
+6
-6
@@ -28,7 +28,7 @@ final class DynamoDbAttributeValueValidator {
|
||||
if (!value.isObject()) {
|
||||
throw serializationEx("Unexpected value type in payload");
|
||||
}
|
||||
var types = TYPES.stream().filter(value::has).toList();
|
||||
List<String> types = TYPES.stream().filter(value::has).toList();
|
||||
if (types.isEmpty()) {
|
||||
throw validationEx("Supplied AttributeValue is empty, must contain exactly one of the supported datatypes");
|
||||
}
|
||||
@@ -69,7 +69,7 @@ final class DynamoDbAttributeValueValidator {
|
||||
if (attributes == null || !attributes.isObject()) {
|
||||
return true;
|
||||
}
|
||||
for (var value : attributes) {
|
||||
for (JsonNode value : attributes) {
|
||||
if (!valueNestingWithinLimit(value)) {
|
||||
return false;
|
||||
}
|
||||
@@ -81,12 +81,12 @@ final class DynamoDbAttributeValueValidator {
|
||||
if (!value.isObject()) {
|
||||
return 1;
|
||||
}
|
||||
var children = value.has("M") ? value.get("M") : value.get("L");
|
||||
JsonNode children = value.has("M") ? value.get("M") : value.get("L");
|
||||
if (children == null) {
|
||||
return 1;
|
||||
}
|
||||
var deepest = 0;
|
||||
for (var child : children) {
|
||||
int deepest = 0;
|
||||
for (JsonNode child : children) {
|
||||
deepest = Math.max(deepest, depthOf(child));
|
||||
}
|
||||
return 1 + deepest;
|
||||
@@ -123,7 +123,7 @@ final class DynamoDbAttributeValueValidator {
|
||||
if (!encoded.isTextual()) {
|
||||
throw serializationEx("only base-64-encoded strings are convertible to bytes");
|
||||
}
|
||||
var text = encoded.asText();
|
||||
String text = encoded.asText();
|
||||
if (text.length() % 4 != 0) {
|
||||
throw serializationEx("Base64 encoded length is expected a multiple of 4 bytes but found: " + text.length());
|
||||
}
|
||||
|
||||
@@ -107,9 +107,9 @@ final class DynamoDbItemSize {
|
||||
static int calculateItemSize(JsonNode item) {
|
||||
if (item == null || !item.isObject()) return 0;
|
||||
int total = 0;
|
||||
var fields = item.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = item.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
total += utf8Length(entry.getKey());
|
||||
total += attributeValueSize(entry.getValue());
|
||||
}
|
||||
@@ -149,9 +149,9 @@ final class DynamoDbItemSize {
|
||||
}
|
||||
if (attr.has("M")) {
|
||||
int size = 0;
|
||||
var fields = attr.get("M").fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = attr.get("M").fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
size += utf8Length(entry.getKey()) + 1 + attributeValueSize(entry.getValue()) + 3;
|
||||
}
|
||||
return size;
|
||||
|
||||
@@ -70,7 +70,7 @@ final class DynamoDbNumberUtils {
|
||||
if (attributes == null || !attributes.isObject()) {
|
||||
return;
|
||||
}
|
||||
for (var value : attributes) {
|
||||
for (JsonNode value : attributes) {
|
||||
requireStorableValue(value, inValidationEnvelope ? "1 validation error detected: " : "");
|
||||
}
|
||||
}
|
||||
@@ -82,13 +82,13 @@ final class DynamoDbNumberUtils {
|
||||
if (value.has("N")) {
|
||||
requireStorableNumber(value.get("N").asText(), prefix);
|
||||
}
|
||||
for (var n : value.path("NS")) {
|
||||
for (JsonNode n : value.path("NS")) {
|
||||
requireStorableNumber(n.asText(), prefix);
|
||||
}
|
||||
for (var element : value.path("L")) {
|
||||
for (JsonNode element : value.path("L")) {
|
||||
requireStorableValue(element, prefix);
|
||||
}
|
||||
for (var entry : value.path("M")) {
|
||||
for (JsonNode entry : value.path("M")) {
|
||||
requireStorableValue(entry, prefix);
|
||||
}
|
||||
}
|
||||
@@ -101,12 +101,12 @@ final class DynamoDbNumberUtils {
|
||||
throw new AwsException("ValidationException",
|
||||
"The parameter cannot be converted to a numeric value: " + numStr, 400);
|
||||
}
|
||||
var stripped = bd.stripTrailingZeros();
|
||||
BigDecimal stripped = bd.stripTrailingZeros();
|
||||
if (stripped.precision() > 38) {
|
||||
throw new AwsException("ValidationException",
|
||||
prefix + "Attempting to store more than 38 significant digits in a Number", 400);
|
||||
}
|
||||
var abs = stripped.abs();
|
||||
BigDecimal abs = stripped.abs();
|
||||
if (abs.compareTo(MAX_ABS) >= 0) {
|
||||
throw new AwsException("ValidationException",
|
||||
prefix + "Number overflow. Attempting to store a number with magnitude larger than supported range", 400);
|
||||
@@ -120,8 +120,8 @@ final class DynamoDbNumberUtils {
|
||||
// AWS answers with the overflow wording for any arithmetic result it cannot store,
|
||||
// a magnitude too small or too many significant digits included.
|
||||
static void checkArithmeticResult(BigDecimal result) {
|
||||
var stripped = result.stripTrailingZeros();
|
||||
var abs = stripped.abs();
|
||||
BigDecimal stripped = result.stripTrailingZeros();
|
||||
BigDecimal abs = stripped.abs();
|
||||
if (stripped.precision() > 38 || abs.compareTo(MAX_ABS) >= 0
|
||||
|| (abs.signum() > 0 && abs.compareTo(MIN_ABS_NONZERO) < 0)) {
|
||||
throw new AwsException("ValidationException",
|
||||
|
||||
+1
-1
@@ -1046,7 +1046,7 @@ public class DynamoDbPartiQLParser {
|
||||
throw validationEx("Not enough parameters supplied for ? placeholders");
|
||||
}
|
||||
JsonNode p = parameters.get(paramIdx++);
|
||||
var type = DynamoDbAttributeValueValidator.typeOf(p);
|
||||
String type = DynamoDbAttributeValueValidator.typeOf(p);
|
||||
return switch (type) {
|
||||
case "S" -> new PVal.Str(p.get("S").asText());
|
||||
case "N" -> new PVal.Num(p.get("N").asText());
|
||||
|
||||
+9
-8
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
@@ -17,14 +18,14 @@ final class DynamoDbUpdatedAttributes {
|
||||
private DynamoDbUpdatedAttributes() {}
|
||||
|
||||
static ObjectNode collect(List<DynamoDbService.TouchedPath> touched, boolean newValues) {
|
||||
var root = new Node();
|
||||
for (var path : touched) {
|
||||
var value = newValues ? path.newValue() : path.oldValue();
|
||||
Node root = new Node();
|
||||
for (DynamoDbService.TouchedPath path : touched) {
|
||||
JsonNode value = newValues ? path.newValue() : path.oldValue();
|
||||
if (value != null) {
|
||||
root.insert(path.tokens(), 0, value);
|
||||
}
|
||||
}
|
||||
var out = JsonNodeFactory.instance.objectNode();
|
||||
ObjectNode out = JsonNodeFactory.instance.objectNode();
|
||||
root.mapChildren.forEach((name, child) -> out.set(name, child.render()));
|
||||
return out;
|
||||
}
|
||||
@@ -44,7 +45,7 @@ final class DynamoDbUpdatedAttributes {
|
||||
listChildren.clear();
|
||||
return;
|
||||
}
|
||||
var child = tokens.get(i) instanceof Long index
|
||||
Node child = tokens.get(i) instanceof Long index
|
||||
? listChildren.computeIfAbsent(index, ignored -> new Node())
|
||||
: mapChildren.computeIfAbsent((String) tokens.get(i), ignored -> new Node());
|
||||
child.insert(tokens, i + 1, value);
|
||||
@@ -54,12 +55,12 @@ final class DynamoDbUpdatedAttributes {
|
||||
if (whole != null) {
|
||||
return whole;
|
||||
}
|
||||
var out = JsonNodeFactory.instance.objectNode();
|
||||
ObjectNode out = JsonNodeFactory.instance.objectNode();
|
||||
if (!listChildren.isEmpty()) {
|
||||
var list = out.putArray("L");
|
||||
ArrayNode list = out.putArray("L");
|
||||
listChildren.values().forEach(child -> list.add(child.render()));
|
||||
} else {
|
||||
var map = out.putObject("M");
|
||||
ObjectNode map = out.putObject("M");
|
||||
mapChildren.forEach((name, child) -> map.set(name, child.render()));
|
||||
}
|
||||
return out;
|
||||
|
||||
+25
-23
@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.dynamodb;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.VectorIndex;
|
||||
|
||||
@@ -46,9 +48,9 @@ final class DynamoDbWriteCapacity {
|
||||
}
|
||||
|
||||
double total() {
|
||||
var sum = table;
|
||||
for (var units : gsi.values()) sum += units;
|
||||
for (var units : lsi.values()) sum += units;
|
||||
double sum = table;
|
||||
for (Double units : gsi.values()) sum += units;
|
||||
for (Double units : lsi.values()) sum += units;
|
||||
return sum;
|
||||
}
|
||||
|
||||
@@ -58,9 +60,9 @@ final class DynamoDbWriteCapacity {
|
||||
}
|
||||
|
||||
Cost plus(Cost other) {
|
||||
var mergedGsi = new LinkedHashMap<>(gsi);
|
||||
LinkedHashMap<String, Double> mergedGsi = new LinkedHashMap<>(gsi);
|
||||
other.gsi().forEach((name, units) -> mergedGsi.merge(name, units, Double::sum));
|
||||
var mergedLsi = new LinkedHashMap<>(lsi);
|
||||
LinkedHashMap<String, Double> mergedLsi = new LinkedHashMap<>(lsi);
|
||||
other.lsi().forEach((name, units) -> mergedLsi.merge(name, units, Double::sum));
|
||||
LinkedHashMap<String, Double> mergedVector = new LinkedHashMap<>(vectorBytes);
|
||||
other.vectorBytes().forEach((name, bytes) -> mergedVector.merge(name, bytes, Double::sum));
|
||||
@@ -70,23 +72,23 @@ final class DynamoDbWriteCapacity {
|
||||
|
||||
/** oldItem and newItem are the stored images before and after the write; either may be null. */
|
||||
static Cost forWrite(TableDefinition table, JsonNode oldItem, JsonNode newItem) {
|
||||
var tableUnits = (double) Math.max(1, Math.max(sizeUnits(oldItem), sizeUnits(newItem)));
|
||||
var gsiUnits = new LinkedHashMap<String, Double>();
|
||||
var gsis = table.getGlobalSecondaryIndexes();
|
||||
double tableUnits = (double) Math.max(1, Math.max(sizeUnits(oldItem), sizeUnits(newItem)));
|
||||
LinkedHashMap<String, Double> gsiUnits = new LinkedHashMap<>();
|
||||
List<GlobalSecondaryIndex> gsis = table.getGlobalSecondaryIndexes();
|
||||
if (gsis != null) {
|
||||
for (var gsi : gsis) {
|
||||
var units = indexUnits(table, gsi.getKeySchema(), gsi.getProjectionType(),
|
||||
for (GlobalSecondaryIndex gsi : gsis) {
|
||||
double units = indexUnits(table, gsi.getKeySchema(), gsi.getProjectionType(),
|
||||
gsi.getNonKeyAttributes(), oldItem, newItem);
|
||||
if (units > 0) {
|
||||
gsiUnits.put(gsi.getIndexName(), units);
|
||||
}
|
||||
}
|
||||
}
|
||||
var lsiUnits = new LinkedHashMap<String, Double>();
|
||||
var lsis = table.getLocalSecondaryIndexes();
|
||||
LinkedHashMap<String, Double> lsiUnits = new LinkedHashMap<>();
|
||||
List<LocalSecondaryIndex> lsis = table.getLocalSecondaryIndexes();
|
||||
if (lsis != null) {
|
||||
for (var lsi : lsis) {
|
||||
var units = indexUnits(table, lsi.getKeySchema(), lsi.getProjectionType(),
|
||||
for (LocalSecondaryIndex lsi : lsis) {
|
||||
double units = indexUnits(table, lsi.getKeySchema(), lsi.getProjectionType(),
|
||||
lsi.getNonKeyAttributes(), oldItem, newItem);
|
||||
if (units > 0) {
|
||||
lsiUnits.put(lsi.getIndexName(), units);
|
||||
@@ -178,8 +180,8 @@ final class DynamoDbWriteCapacity {
|
||||
if (keySchema == null) {
|
||||
return 0;
|
||||
}
|
||||
var oldView = indexView(table, keySchema, projectionType, nonKeyAttributes, oldItem);
|
||||
var newView = indexView(table, keySchema, projectionType, nonKeyAttributes, newItem);
|
||||
JsonNode oldView = indexView(table, keySchema, projectionType, nonKeyAttributes, oldItem);
|
||||
JsonNode newView = indexView(table, keySchema, projectionType, nonKeyAttributes, newItem);
|
||||
if (oldView == null) {
|
||||
if (newView == null) {
|
||||
return 0;
|
||||
@@ -208,7 +210,7 @@ final class DynamoDbWriteCapacity {
|
||||
if (item == null) {
|
||||
return null;
|
||||
}
|
||||
for (var element : keySchema) {
|
||||
for (KeySchemaElement element : keySchema) {
|
||||
if (!item.has(element.getAttributeName())) {
|
||||
return null;
|
||||
}
|
||||
@@ -216,19 +218,19 @@ final class DynamoDbWriteCapacity {
|
||||
if (projectionType == null || "ALL".equals(projectionType)) {
|
||||
return item;
|
||||
}
|
||||
var keep = new LinkedHashSet<String>();
|
||||
LinkedHashSet<String> keep = new LinkedHashSet<>();
|
||||
keep.add(table.getPartitionKeyName());
|
||||
if (table.getSortKeyName() != null) {
|
||||
keep.add(table.getSortKeyName());
|
||||
}
|
||||
for (var element : keySchema) {
|
||||
for (KeySchemaElement element : keySchema) {
|
||||
keep.add(element.getAttributeName());
|
||||
}
|
||||
if ("INCLUDE".equals(projectionType) && nonKeyAttributes != null) {
|
||||
keep.addAll(nonKeyAttributes);
|
||||
}
|
||||
var view = JsonNodeFactory.instance.objectNode();
|
||||
for (var name : keep) {
|
||||
ObjectNode view = JsonNodeFactory.instance.objectNode();
|
||||
for (String name : keep) {
|
||||
if (item.has(name)) {
|
||||
view.set(name, item.get(name));
|
||||
}
|
||||
@@ -238,8 +240,8 @@ final class DynamoDbWriteCapacity {
|
||||
|
||||
private static boolean indexKeyChanged(List<KeySchemaElement> keySchema,
|
||||
JsonNode oldItem, JsonNode newItem) {
|
||||
for (var element : keySchema) {
|
||||
var name = element.getAttributeName();
|
||||
for (KeySchemaElement element : keySchema) {
|
||||
String name = element.getAttributeName();
|
||||
if (!oldItem.get(name).equals(newItem.get(name))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
+30
-26
@@ -10,7 +10,11 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Proper tokenizer/parser/evaluator for DynamoDB filter expressions and key condition expressions.
|
||||
@@ -51,7 +55,7 @@ final class ExpressionEvaluator {
|
||||
// ── Tokenizer ──
|
||||
|
||||
static List<Token> tokenize(String expression) {
|
||||
var tokens = new ArrayList<Token>();
|
||||
ArrayList<Token> tokens = new ArrayList<>();
|
||||
int i = 0;
|
||||
int len = expression.length();
|
||||
|
||||
@@ -218,7 +222,7 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
|
||||
private Expr parseOrExpr() {
|
||||
var operands = new ArrayList<Expr>();
|
||||
ArrayList<Expr> operands = new ArrayList<>();
|
||||
operands.add(parseAndExpr());
|
||||
while (peek().type() == TokenType.OR) {
|
||||
advance(); // consume OR
|
||||
@@ -228,7 +232,7 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
|
||||
private Expr parseAndExpr() {
|
||||
var operands = new ArrayList<Expr>();
|
||||
ArrayList<Expr> operands = new ArrayList<>();
|
||||
operands.add(parseNotExpr());
|
||||
while (peek().type() == TokenType.AND) {
|
||||
advance(); // consume AND
|
||||
@@ -260,7 +264,7 @@ final class ExpressionEvaluator {
|
||||
if (current.type() == TokenType.FUNCTION) {
|
||||
String funcName = advance().value();
|
||||
expect(TokenType.LPAREN);
|
||||
var args = parseOperandList();
|
||||
List<Operand> args = parseOperandList();
|
||||
expect(TokenType.RPAREN);
|
||||
|
||||
// If followed by a comparator, this is "size(path) = :val" — treat as comparison
|
||||
@@ -280,7 +284,7 @@ final class ExpressionEvaluator {
|
||||
if (next.type() == TokenType.IN) {
|
||||
advance(); // consume IN
|
||||
expect(TokenType.LPAREN);
|
||||
var candidates = parseOperandList();
|
||||
List<Operand> candidates = parseOperandList();
|
||||
expect(TokenType.RPAREN);
|
||||
return new InExpr(left, candidates);
|
||||
}
|
||||
@@ -309,7 +313,7 @@ final class ExpressionEvaluator {
|
||||
if (current.type() == TokenType.FUNCTION) {
|
||||
String funcName = advance().value();
|
||||
expect(TokenType.LPAREN);
|
||||
var args = parseOperandList();
|
||||
List<Operand> args = parseOperandList();
|
||||
expect(TokenType.RPAREN);
|
||||
return new FunctionOperand(funcName, args);
|
||||
}
|
||||
@@ -321,7 +325,7 @@ final class ExpressionEvaluator {
|
||||
|
||||
// Path: identifier or #name, possibly dotted with nested [n] list indices
|
||||
if (current.type() == TokenType.IDENTIFIER || current.type() == TokenType.NAME_REF) {
|
||||
var segments = new ArrayList<String>();
|
||||
ArrayList<String> segments = new ArrayList<>();
|
||||
segments.add(advance().value());
|
||||
// Consume any immediately-following list indices (no dot needed before [n])
|
||||
while (peek().type() == TokenType.LIST_INDEX) {
|
||||
@@ -350,7 +354,7 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
|
||||
private List<Operand> parseOperandList() {
|
||||
var list = new ArrayList<Operand>();
|
||||
ArrayList<Operand> list = new ArrayList<>();
|
||||
list.add(parseOperand());
|
||||
while (peek().type() == TokenType.COMMA) {
|
||||
advance(); // consume comma
|
||||
@@ -370,8 +374,8 @@ final class ExpressionEvaluator {
|
||||
|
||||
static Expr parse(String expression) {
|
||||
if (expression == null || expression.isBlank()) return null;
|
||||
var tokens = tokenize(expression.trim());
|
||||
var parser = new Parser(tokens);
|
||||
List<Token> tokens = tokenize(expression.trim());
|
||||
Parser parser = new Parser(tokens);
|
||||
Expr expr = parser.parseExpression();
|
||||
if (parser.peek().type() != TokenType.EOF) {
|
||||
throw new IllegalArgumentException(
|
||||
@@ -477,12 +481,12 @@ final class ExpressionEvaluator {
|
||||
// AWS rejects a BETWEEN whose bounds are the wrong way round when it parses the
|
||||
// expression, rather than letting the condition fail at evaluation time.
|
||||
private static void validateBetween(BetweenExpr between, String exprType, JsonNode values) {
|
||||
var low = placeholderValue(between.low(), values);
|
||||
var high = placeholderValue(between.high(), values);
|
||||
JsonNode low = placeholderValue(between.low(), values);
|
||||
JsonNode high = placeholderValue(between.high(), values);
|
||||
if (low == null || high == null) {
|
||||
return;
|
||||
}
|
||||
var lowType = low.fieldNames().next();
|
||||
String lowType = low.fieldNames().next();
|
||||
if (!lowType.equals(high.fieldNames().next()) || compareBoundValues(low, high) <= 0) {
|
||||
return;
|
||||
}
|
||||
@@ -522,7 +526,7 @@ final class ExpressionEvaluator {
|
||||
|
||||
private static JsonNode placeholderValue(Operand operand, JsonNode values) {
|
||||
if (operand instanceof PlaceholderOperand(String name) && values != null) {
|
||||
var value = values.get(name);
|
||||
JsonNode value = values.get(name);
|
||||
if (value != null && value.isObject() && value.fieldNames().hasNext()) {
|
||||
return value;
|
||||
}
|
||||
@@ -531,7 +535,7 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
|
||||
private static String displayAttributeValue(JsonNode value) {
|
||||
var type = value.fieldNames().next();
|
||||
String type = value.fieldNames().next();
|
||||
return "AttributeValue: {" + type + ":" + value.get(type).asText() + "}";
|
||||
}
|
||||
|
||||
@@ -580,7 +584,7 @@ final class ExpressionEvaluator {
|
||||
// Renders a path operand the way DynamoDB does in operand errors, e.g. "[data]" or "[a, b]".
|
||||
private static String displayOperand(Operand operand, JsonNode names) {
|
||||
if (operand instanceof PathOperand path) {
|
||||
var parts = new ArrayList<String>();
|
||||
ArrayList<String> parts = new ArrayList<>();
|
||||
for (String seg : path.segments()) {
|
||||
if (seg.startsWith("[")) {
|
||||
if (!parts.isEmpty()) parts.set(parts.size() - 1, parts.getLast() + seg);
|
||||
@@ -623,7 +627,7 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
}
|
||||
|
||||
var tokens = tokenize(expression.trim());
|
||||
List<Token> tokens = tokenize(expression.trim());
|
||||
// Find the top-level AND that separates PK from SK.
|
||||
// We need to skip AND tokens that are part of BETWEEN...AND.
|
||||
// Strategy: walk through tokens tracking parenthesis depth and BETWEEN state.
|
||||
@@ -937,7 +941,7 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
|
||||
private static String resolvePathString(PathOperand path, JsonNode exprAttrNames) {
|
||||
var sb = new StringBuilder();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < path.segments().size(); i++) {
|
||||
String segment = path.segments().get(i);
|
||||
if (segment.startsWith("[")) {
|
||||
@@ -979,7 +983,7 @@ final class ExpressionEvaluator {
|
||||
// Tokenizes a resolved path string (e.g. "a.b[0].c") into segments.
|
||||
// Each segment is either a plain attribute name or a "[n]" list index string.
|
||||
private static List<String> parsePathSegments(String path) {
|
||||
var segs = new ArrayList<String>();
|
||||
ArrayList<String> segs = new ArrayList<>();
|
||||
for (String dotPart : path.split("\\.")) {
|
||||
dotPart = dotPart.replace(DOT_ESCAPE, ".");
|
||||
int brk = dotPart.indexOf('[');
|
||||
@@ -1046,9 +1050,9 @@ final class ExpressionEvaluator {
|
||||
JsonNode aMap = a.get("M");
|
||||
JsonNode bMap = b.get("M");
|
||||
if (aMap.size() != bMap.size()) return false;
|
||||
var fields = aMap.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = aMap.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
if (!bMap.has(entry.getKey())) return false;
|
||||
if (!attributeValuesEqual(entry.getValue(), bMap.get(entry.getKey()))) return false;
|
||||
}
|
||||
@@ -1067,7 +1071,7 @@ final class ExpressionEvaluator {
|
||||
if (a.has("SS") && b.has("SS")) {
|
||||
JsonNode aArr = a.get("SS"), bArr = b.get("SS");
|
||||
if (aArr.size() != bArr.size()) return false;
|
||||
var aSet = new java.util.HashSet<String>();
|
||||
HashSet<String> aSet = new HashSet<>();
|
||||
aArr.forEach(e -> aSet.add(e.asText()));
|
||||
for (JsonNode e : bArr) { if (!aSet.contains(e.asText())) return false; }
|
||||
return true;
|
||||
@@ -1076,7 +1080,7 @@ final class ExpressionEvaluator {
|
||||
if (a.has("BS") && b.has("BS")) {
|
||||
JsonNode aArr = a.get("BS"), bArr = b.get("BS");
|
||||
if (aArr.size() != bArr.size()) return false;
|
||||
var aSet = new java.util.HashSet<String>();
|
||||
HashSet<String> aSet = new HashSet<>();
|
||||
aArr.forEach(e -> aSet.add(e.asText()));
|
||||
for (JsonNode e : bArr) { if (!aSet.contains(e.asText())) return false; }
|
||||
return true;
|
||||
@@ -1087,7 +1091,7 @@ final class ExpressionEvaluator {
|
||||
if (aArr.size() != bArr.size()) return false;
|
||||
// TreeSet membership goes through compareTo, so 1 and 1.0 are the same member.
|
||||
// BigDecimal.equals() is scale-sensitive and would treat them as different.
|
||||
var aSet = new java.util.TreeSet<BigDecimal>();
|
||||
TreeSet<BigDecimal> aSet = new TreeSet<>();
|
||||
try {
|
||||
aArr.forEach(e -> aSet.add(new BigDecimal(e.asText())));
|
||||
for (JsonNode e : bArr) { if (!aSet.contains(new BigDecimal(e.asText()))) return false; }
|
||||
@@ -1116,8 +1120,8 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
}
|
||||
if (a.has("B") && b.has("B")) {
|
||||
var aBytes = decodeBinaryBound(a);
|
||||
var bBytes = decodeBinaryBound(b);
|
||||
byte[] aBytes = decodeBinaryBound(a);
|
||||
byte[] bBytes = decodeBinaryBound(b);
|
||||
int minLen = Math.min(aBytes.length, bBytes.length);
|
||||
for (int i = 0; i < minLen; i++) {
|
||||
int diff = (aBytes[i] & 0xFF) - (bBytes[i] & 0xFF);
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -64,7 +65,7 @@ final class ProjectionEvaluator {
|
||||
}
|
||||
|
||||
static Set<String> topLevelAttributes(String projectionExpression, JsonNode exprAttrNames) {
|
||||
var attributes = new java.util.HashSet<String>();
|
||||
HashSet<String> attributes = new HashSet<>();
|
||||
for (String rawPath : splitProjectionPaths(projectionExpression)) {
|
||||
List<PathSegment> segments = resolvePath(rawPath.trim(), exprAttrNames);
|
||||
if (!segments.isEmpty()) {
|
||||
@@ -222,11 +223,11 @@ final class ProjectionEvaluator {
|
||||
if (content.isEmpty()) {
|
||||
throw syntaxError("ProjectionExpression", "]", "[]");
|
||||
}
|
||||
final var contentLength = content.length();
|
||||
for (var i = 0; i < contentLength; i++) {
|
||||
var c = content.charAt(i);
|
||||
final int contentLength = content.length();
|
||||
for (int i = 0; i < contentLength; i++) {
|
||||
char c = content.charAt(i);
|
||||
if (c < '0' || '9' < c) {
|
||||
var near = "[" + content + "]";
|
||||
String near = "[" + content + "]";
|
||||
throw syntaxError("ProjectionExpression", String.valueOf(c),
|
||||
near.substring(0, Math.min(3, near.length())));
|
||||
}
|
||||
|
||||
@@ -756,12 +756,12 @@ public class Ec2IpamService {
|
||||
Optional<AccountAwareStorageBackend.OwnedEntry<Ipam>> exact =
|
||||
accountAware.findAnyAccountEntry(key(region, ipamId));
|
||||
if (exact.isPresent()) {
|
||||
var entry = exact.get();
|
||||
AccountAwareStorageBackend.OwnedEntry<Ipam> entry = exact.get();
|
||||
return new OwnedIpam(entry.account(), entry.value());
|
||||
}
|
||||
for (Ipam ipam : accountAware.scanAllAccounts()) {
|
||||
if (ipam.getIpamId().equals(ipamId)) {
|
||||
var entry = accountAware.findAnyAccountEntry(
|
||||
AccountAwareStorageBackend.OwnedEntry<Ipam> entry = accountAware.findAnyAccountEntry(
|
||||
key(ipam.getRegion(), ipam.getIpamId())).orElseThrow();
|
||||
return new OwnedIpam(entry.account(), entry.value());
|
||||
}
|
||||
@@ -846,12 +846,12 @@ public class Ec2IpamService {
|
||||
Optional<AccountAwareStorageBackend.OwnedEntry<IpamPool>> exact =
|
||||
accountAware.findAnyAccountEntry(key(region, ipamPoolId));
|
||||
if (exact.isPresent()) {
|
||||
var entry = exact.get();
|
||||
AccountAwareStorageBackend.OwnedEntry<IpamPool> entry = exact.get();
|
||||
return new OwnedPool(entry.account(), entry.value());
|
||||
}
|
||||
for (IpamPool pool : accountAware.scanAllAccounts()) {
|
||||
if (pool.getIpamPoolId().equals(ipamPoolId)) {
|
||||
var entry = accountAware.findAnyAccountEntry(
|
||||
AccountAwareStorageBackend.OwnedEntry<IpamPool> entry = accountAware.findAnyAccountEntry(
|
||||
key(pool.getRegion(), pool.getIpamPoolId())).orElseThrow();
|
||||
return new OwnedPool(entry.account(), entry.value());
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
@@ -258,7 +260,7 @@ public class Ec2MetadataServer {
|
||||
return;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (var sg : inst.getSecurityGroups()) {
|
||||
for (GroupIdentifier sg : inst.getSecurityGroups()) {
|
||||
if (!sb.isEmpty()) {
|
||||
sb.append("\n");
|
||||
}
|
||||
@@ -469,7 +471,7 @@ public class Ec2MetadataServer {
|
||||
if (instance == null || instance.getTags() == null) {
|
||||
return "";
|
||||
}
|
||||
for (var tag : instance.getTags()) {
|
||||
for (Tag tag : instance.getTags()) {
|
||||
if (tag.getKey() == null || tag.getKey().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
@@ -485,7 +487,7 @@ public class Ec2MetadataServer {
|
||||
if (instance == null || instance.getTags() == null || key == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
for (var tag : instance.getTags()) {
|
||||
for (Tag tag : instance.getTags()) {
|
||||
if (key.equals(tag.getKey())) {
|
||||
return Optional.of(nvl(tag.getValue()));
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -236,7 +237,7 @@ public class EcrService implements ResourceProvider {
|
||||
String defaultAccount = regionResolver.getAccountId();
|
||||
String defaultRegion = regionResolver.getDefaultRegion();
|
||||
String legacyKey = key(defaultRegion, defaultAccount, registryRepositoryName);
|
||||
var legacyRepository = repoStore.get(legacyKey);
|
||||
Optional<Repository> legacyRepository = repoStore.get(legacyKey);
|
||||
if (legacyRepository.isPresent()) {
|
||||
Repository repo = legacyRepository.get();
|
||||
repo.setRepositoryUri(registryManager.getRepositoryUri(
|
||||
@@ -252,7 +253,7 @@ public class EcrService implements ResourceProvider {
|
||||
String region = namespaced ? parts[1] : defaultRegion;
|
||||
String repoName = namespaced ? parts[2] : registryRepositoryName;
|
||||
String key = key(region, account, repoName);
|
||||
var existing = repoStore.get(key);
|
||||
Optional<Repository> existing = repoStore.get(key);
|
||||
if (existing.isPresent()) {
|
||||
Repository repo = existing.get();
|
||||
repo.setRepositoryUri(registryManager.getRepositoryUri(account, region, repoName));
|
||||
|
||||
+3
-2
@@ -34,6 +34,7 @@ import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -284,7 +285,7 @@ public class EcrRegistryManager {
|
||||
// Check for existing container to adopt. The registry survives shutdown by design and is
|
||||
// adopted BY NAME, so look up the pre-migration name too: otherwise an upgraded emulator
|
||||
// orphans the old container while it still holds the registry host port and its data.
|
||||
var existing = lifecycleManager.findByName(name);
|
||||
Optional<Container> existing = lifecycleManager.findByName(name);
|
||||
String adoptedName = name;
|
||||
if (existing.isEmpty()) {
|
||||
adoptedName = legacyRegistryContainerName();
|
||||
@@ -630,7 +631,7 @@ public class EcrRegistryManager {
|
||||
ContainerInfo info = lifecycleManager.adopt(containerId, List.of(CONTAINER_INTERNAL_PORT));
|
||||
// The control plane reaches the backing registry through this published loopback
|
||||
// binding when Floci runs on the host. In Docker, httpClient() uses container DNS.
|
||||
var published = info.publishedHostPort(CONTAINER_INTERNAL_PORT);
|
||||
OptionalInt published = info.publishedHostPort(CONTAINER_INTERNAL_PORT);
|
||||
if (published.isPresent()) {
|
||||
this.hostPort = published.getAsInt();
|
||||
} else {
|
||||
|
||||
+15
-11
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
@@ -27,6 +28,7 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.FirelensConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
|
||||
import io.github.hectorvent.floci.services.ecs.model.LogConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ManagedAgent;
|
||||
import io.github.hectorvent.floci.services.ecs.model.MountPoint;
|
||||
@@ -42,6 +44,7 @@ import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService.Lau
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
@@ -53,6 +56,7 @@ import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.LogConfig;
|
||||
import com.github.dockerjava.api.model.StatisticNetworksConfig;
|
||||
import com.github.dockerjava.api.model.Statistics;
|
||||
import io.github.hectorvent.floci.services.ssm.model.Parameter;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
@@ -1809,7 +1813,7 @@ public class EcsContainerManager {
|
||||
*/
|
||||
public Integer getExitCodeIfStopped(String dockerId) {
|
||||
try {
|
||||
var inspect = lifecycleManager.getDockerClient().inspectContainerCmd(dockerId).exec();
|
||||
InspectContainerResponse inspect = lifecycleManager.getDockerClient().inspectContainerCmd(dockerId).exec();
|
||||
if (Boolean.TRUE.equals(inspect.getState().getRunning())) {
|
||||
return null;
|
||||
}
|
||||
@@ -1852,7 +1856,7 @@ public class EcsContainerManager {
|
||||
envMap.put("ECS_CONTAINER_METADATA_URI_V4", flociEndpoint + "/v4/" + metadataId);
|
||||
}
|
||||
if (def.getEnvironment() != null) {
|
||||
for (var kv : def.getEnvironment()) {
|
||||
for (KeyValuePair kv : def.getEnvironment()) {
|
||||
envMap.put(kv.name(), kv.value());
|
||||
}
|
||||
}
|
||||
@@ -1862,12 +1866,12 @@ public class EcsContainerManager {
|
||||
}
|
||||
}
|
||||
if (override != null && override.getEnvironment() != null) {
|
||||
for (var kv : override.getEnvironment()) {
|
||||
for (KeyValuePair kv : override.getEnvironment()) {
|
||||
envMap.put(kv.name(), kv.value());
|
||||
}
|
||||
}
|
||||
List<String> envVars = new ArrayList<>();
|
||||
for (var entry : envMap.entrySet()) {
|
||||
for (Map.Entry<String, String> entry : envMap.entrySet()) {
|
||||
envVars.add(entry.getKey() + "=" + entry.getValue());
|
||||
}
|
||||
return envVars;
|
||||
@@ -1898,14 +1902,14 @@ public class EcsContainerManager {
|
||||
// The valueFrom may carry the ECS selector suffix
|
||||
// (:json-key:version-stage:version-id); the parser strips it so the base ARN
|
||||
// reaches SecretsManagerService intact, keeping its partial-ARN fallback working.
|
||||
var selector = SecretsManagerSelector.parse(valueFrom);
|
||||
SecretsManagerSelector selector = SecretsManagerSelector.parse(valueFrom);
|
||||
jsonKey = selector.jsonKey();
|
||||
var secret = secretsManagerService.getSecretValue(selector.secretId(),
|
||||
SecretVersion secret = secretsManagerService.getSecretValue(selector.secretId(),
|
||||
selector.versionId(), selector.versionStage(), secretRegion);
|
||||
value = secret == null ? null : secret.getSecretString();
|
||||
} else {
|
||||
String parameterName = ssmParameterName(valueFrom);
|
||||
var parameter = ssmService.getParameter(parameterName, secretRegion);
|
||||
Parameter parameter = ssmService.getParameter(parameterName, secretRegion);
|
||||
value = parameter == null ? null : parameter.getValue();
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
@@ -2053,12 +2057,12 @@ public class EcsContainerManager {
|
||||
}
|
||||
|
||||
DockerClient dockerClient = lifecycleManager.getDockerClient();
|
||||
var inspect = dockerClient.inspectContainerCmd(dockerId).exec();
|
||||
var portBindingsMap = inspect.getNetworkSettings().getPorts().getBindings();
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(dockerId).exec();
|
||||
Map<ExposedPort, Ports.Binding[]> portBindingsMap = inspect.getNetworkSettings().getPorts().getBindings();
|
||||
|
||||
for (PortMapping pm : def.getPortMappings()) {
|
||||
ExposedPort ep = ExposedPort.tcp(pm.containerPort());
|
||||
var binding = portBindingsMap.get(ep);
|
||||
Ports.Binding[] binding = portBindingsMap.get(ep);
|
||||
int hostPort = pm.containerPort();
|
||||
String bindIp = "0.0.0.0";
|
||||
|
||||
@@ -2172,7 +2176,7 @@ public class EcsContainerManager {
|
||||
*/
|
||||
private void mountEfsVolume(ContainerBuilder.Builder specBuilder, EfsVolumeConfiguration efs, MountPoint mp) {
|
||||
String efsVolumeName = efsVolumeName(efs.fileSystemId(), efs.accessPointId(), efs.rootDirectory());
|
||||
var efsCfg = config.storage().efs();
|
||||
EmulatorConfig.EfsSharingConfig efsCfg = config.storage().efs();
|
||||
lifecycleManager.ensureSharedVolume(efsVolumeName,
|
||||
efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(),
|
||||
efsCfg.initImage());
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -73,7 +74,7 @@ public class EksOidcWellKnownController {
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"No OIDC signing key for cluster: " + clusterName, 404));
|
||||
|
||||
var publicKey = oidcService.toPublicKey(key.getPublicKey());
|
||||
RSAPublicKey publicKey = oidcService.toPublicKey(key.getPublicKey());
|
||||
Map<String, Object> jwk = new LinkedHashMap<>();
|
||||
jwk.put("kty", "RSA");
|
||||
jwk.put("alg", "RS256");
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.firehose;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.KinesisStreamSource;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.S3Destination;
|
||||
import io.github.hectorvent.floci.services.firehose.model.Record;
|
||||
@@ -115,7 +116,7 @@ public class FirehoseJsonHandler {
|
||||
}
|
||||
case "DescribeDeliveryStream" -> {
|
||||
String name = getDeliveryStreamName(request);
|
||||
var desc = firehoseService.describeDeliveryStream(name);
|
||||
DeliveryStreamDescription desc = firehoseService.describeDeliveryStream(name);
|
||||
yield Response.ok(Map.of("DeliveryStreamDescription", desc)).build();
|
||||
}
|
||||
case "ListDeliveryStreams" -> {
|
||||
@@ -174,7 +175,7 @@ public class FirehoseJsonHandler {
|
||||
|
||||
List<io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.Tag> tags = firehoseService.listTagsForDeliveryStream(name, exclusiveStartTagKey, limit);
|
||||
boolean hasMore = false;
|
||||
var allTags = firehoseService.describeDeliveryStream(name).getTags();
|
||||
List<DeliveryStreamDescription.Tag> allTags = firehoseService.describeDeliveryStream(name).getTags();
|
||||
if (!tags.isEmpty() && !allTags.isEmpty()) {
|
||||
String lastKey = tags.get(tags.size() - 1).getKey();
|
||||
int idx = -1;
|
||||
|
||||
+2
-2
@@ -357,9 +357,9 @@ public class FirehoseParquetConverter {
|
||||
// schema over a 128 MiB batch would otherwise cost columns x fields.
|
||||
// First occurrence wins, as the per-column scan it replaces did.
|
||||
Map<String, JsonNode> byLowerKey = new LinkedHashMap<>();
|
||||
var fields = record.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = record.fields();
|
||||
while (fields.hasNext()) {
|
||||
var field = fields.next();
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
byLowerKey.putIfAbsent(field.getKey().toLowerCase(Locale.ROOT), field.getValue());
|
||||
}
|
||||
return byLowerKey;
|
||||
|
||||
+4
-3
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OpenXJsonSerDe;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.OrcSerDe;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription.ParquetSerDe;
|
||||
@@ -128,7 +129,7 @@ final class S3DestinationValidator {
|
||||
*/
|
||||
private static void collectSchemaViolations(S3Destination config, String shapeName,
|
||||
List<String> violations) {
|
||||
var conversion = config.getDataFormatConversionConfiguration();
|
||||
DeliveryStreamDescription.DataFormatConversionConfiguration conversion = config.getDataFormatConversionConfiguration();
|
||||
if (conversion == null || conversion.getSchemaConfiguration() == null) {
|
||||
return;
|
||||
}
|
||||
@@ -168,7 +169,7 @@ final class S3DestinationValidator {
|
||||
*/
|
||||
private static void collectOpenXMappingViolations(S3Destination config, String shapeName,
|
||||
List<String> violations) {
|
||||
var conversion = config.getDataFormatConversionConfiguration();
|
||||
DeliveryStreamDescription.DataFormatConversionConfiguration conversion = config.getDataFormatConversionConfiguration();
|
||||
if (conversion == null || conversion.getInputFormatConfiguration() == null
|
||||
|| conversion.getInputFormatConfiguration().getDeserializer() == null) {
|
||||
return;
|
||||
@@ -214,7 +215,7 @@ final class S3DestinationValidator {
|
||||
}
|
||||
|
||||
private static Serializer serializer(S3Destination config) {
|
||||
var conversion = config.getDataFormatConversionConfiguration();
|
||||
DeliveryStreamDescription.DataFormatConversionConfiguration conversion = config.getDataFormatConversionConfiguration();
|
||||
if (conversion == null || conversion.getOutputFormatConfiguration() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -1112,8 +1113,8 @@ public class FisService implements TagHandler {
|
||||
private Set<String> persistResolvedTargets(String region, String experimentId, JsonNode targets) {
|
||||
Set<String> unresolvedTargets = new HashSet<>();
|
||||
int index = 0;
|
||||
for (var iterator = targets.fields(); iterator.hasNext();) {
|
||||
var entry = iterator.next();
|
||||
for (Iterator<Map.Entry<String, JsonNode>> iterator = targets.fields(); iterator.hasNext();) {
|
||||
Map.Entry<String, JsonNode> entry = iterator.next();
|
||||
String targetName = entry.getKey();
|
||||
JsonNode target = entry.getValue();
|
||||
String resourceType = target.path("resourceType").asText();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.floci.ui;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
@@ -658,7 +659,7 @@ public class FlociUiManager {
|
||||
return new RuntimeProbe(true, null);
|
||||
}
|
||||
JsonNode health;
|
||||
try (var input = conn.getInputStream()) {
|
||||
try (InputStream input = conn.getInputStream()) {
|
||||
health = objectMapper.readTree(input);
|
||||
}
|
||||
String reported = health.path(console.healthReadyField()).asText("");
|
||||
|
||||
@@ -780,7 +780,7 @@ public class GlueJsonHandler {
|
||||
String dbName = request.path("DatabaseName").asText(null);
|
||||
String pattern = request.path("Pattern").asText(null);
|
||||
String functionType = request.path("FunctionType").asText(null);
|
||||
var page = glueService.getUserDefinedFunctions(
|
||||
GlueService.UserDefinedFunctionPage page = glueService.getUserDefinedFunctions(
|
||||
dbName, pattern, functionType, readMaxResults(request), readNextToken(request));
|
||||
return Response.ok(pageResponse("UserDefinedFunctions", page.functions(), page.nextToken())).build();
|
||||
}
|
||||
@@ -818,7 +818,7 @@ public class GlueJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleListRegistries(JsonNode request) {
|
||||
var page = schemaRegistryService.listRegistries(readMaxResults(request), readNextToken(request));
|
||||
GlueSchemaRegistryService.Page<Registry> page = schemaRegistryService.listRegistries(readMaxResults(request), readNextToken(request));
|
||||
return Response.ok(pageResponse("Registries", registryListItems(page.items()), page.nextToken())).build();
|
||||
}
|
||||
|
||||
@@ -869,7 +869,7 @@ public class GlueJsonHandler {
|
||||
Map<String, String> tags = request.has("Tags")
|
||||
? mapper.convertValue(request.get("Tags"), Map.class)
|
||||
: null;
|
||||
var result = schemaRegistryService.createSchema(
|
||||
GlueSchemaRegistryService.SchemaWithFirstVersion result = schemaRegistryService.createSchema(
|
||||
registryId, schemaName, dataFormat, compatibility, description, definition, tags, region);
|
||||
Schema schema = result.schema();
|
||||
SchemaVersion version = result.firstVersion();
|
||||
@@ -958,14 +958,14 @@ public class GlueJsonHandler {
|
||||
|
||||
private Response handleListSchemas(JsonNode request, String region) throws Exception {
|
||||
RegistryId registryId = readRegistryId(request);
|
||||
var page = schemaRegistryService.listSchemas(
|
||||
GlueSchemaRegistryService.Page<Schema> page = schemaRegistryService.listSchemas(
|
||||
registryId, region, readMaxResults(request), readNextToken(request));
|
||||
return Response.ok(pageResponse("Schemas", schemaListItems(page.items()), page.nextToken())).build();
|
||||
}
|
||||
|
||||
private Response handleListSchemaVersions(JsonNode request, String region) throws Exception {
|
||||
SchemaId schemaId = readSchemaId(request);
|
||||
var page = schemaRegistryService.listSchemaVersions(
|
||||
GlueSchemaRegistryService.Page<SchemaVersion> page = schemaRegistryService.listSchemaVersions(
|
||||
schemaId, region, readMaxResults(request), readNextToken(request));
|
||||
return Response.ok(pageResponse("Schemas", schemaVersionListItems(page.items()), page.nextToken())).build();
|
||||
}
|
||||
@@ -983,10 +983,10 @@ public class GlueJsonHandler {
|
||||
private Response handleDeleteSchemaVersions(JsonNode request, String region) throws Exception {
|
||||
SchemaId schemaId = readSchemaId(request);
|
||||
String versions = request.path("Versions").asText(null);
|
||||
var results = schemaRegistryService.deleteSchemaVersions(schemaId, versions, region);
|
||||
List<GlueSchemaRegistryService.VersionDeletionResult> results = schemaRegistryService.deleteSchemaVersions(schemaId, versions, region);
|
||||
|
||||
List<Map<String, Object>> errors = new ArrayList<>();
|
||||
for (var r : results) {
|
||||
for (GlueSchemaRegistryService.VersionDeletionResult r : results) {
|
||||
if (r.errorCode() != null) {
|
||||
Map<String, Object> err = new LinkedHashMap<>();
|
||||
err.put("VersionNumber", r.versionNumber());
|
||||
@@ -1013,7 +1013,7 @@ public class GlueJsonHandler {
|
||||
private Response handleCheckSchemaVersionValidity(JsonNode request) {
|
||||
String dataFormat = request.path("DataFormat").asText(null);
|
||||
String definition = request.path("SchemaDefinition").asText(null);
|
||||
var result = schemaRegistryService.checkSchemaVersionValidity(dataFormat, definition);
|
||||
GlueSchemaRegistryService.CheckValidityResult result = schemaRegistryService.checkSchemaVersionValidity(dataFormat, definition);
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("Valid", result.valid());
|
||||
if (result.error() != null) {
|
||||
@@ -1119,7 +1119,7 @@ public class GlueJsonHandler {
|
||||
JsonNode kv = request.get("MetadataKeyValue");
|
||||
String key = kv != null ? kv.path("MetadataKey").asText(null) : null;
|
||||
String value = kv != null ? kv.path("MetadataValue").asText(null) : null;
|
||||
var result = schemaRegistryService.putSchemaVersionMetadata(svId, key, value);
|
||||
GlueSchemaRegistryService.MetadataPutResult result = schemaRegistryService.putSchemaVersionMetadata(svId, key, value);
|
||||
return Response.ok(buildMetadataPutResponse(result)).build();
|
||||
}
|
||||
|
||||
@@ -1128,7 +1128,7 @@ public class GlueJsonHandler {
|
||||
JsonNode kv = request.get("MetadataKeyValue");
|
||||
String key = kv != null ? kv.path("MetadataKey").asText(null) : null;
|
||||
String value = kv != null ? kv.path("MetadataValue").asText(null) : null;
|
||||
var result = schemaRegistryService.removeSchemaVersionMetadata(svId, key, value);
|
||||
GlueSchemaRegistryService.MetadataPutResult result = schemaRegistryService.removeSchemaVersionMetadata(svId, key, value);
|
||||
return Response.ok(buildMetadataPutResponse(result)).build();
|
||||
}
|
||||
|
||||
|
||||
@@ -320,7 +320,7 @@ public class IamQueryHandler {
|
||||
private Response handleListUsers(MultivaluedMap<String, String> params) {
|
||||
String pathPrefix = getParam(params, "PathPrefix");
|
||||
List<IamUser> userList = iamService.listUsers(pathPrefix);
|
||||
var xml = new XmlBuilder().start("Users");
|
||||
XmlBuilder xml = new XmlBuilder().start("Users");
|
||||
for (IamUser u : userList) {
|
||||
xml.start("member").raw(userXml(u, false)).end("member");
|
||||
}
|
||||
@@ -526,7 +526,7 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleListSAMLProviders(String authorization) {
|
||||
var xml = new XmlBuilder().start("SAMLProviderList");
|
||||
XmlBuilder xml = new XmlBuilder().start("SAMLProviderList");
|
||||
for (SAMLProvider provider : samlProviderService.list(accountResolver.resolve(authorization))) {
|
||||
xml.start("member").elem("Arn", provider.getArn()).end("member");
|
||||
}
|
||||
@@ -593,7 +593,7 @@ public class IamQueryHandler {
|
||||
// ListOpenIDConnectProviders is not paginated and carries only ARNs — the client fetches
|
||||
// the rest with GetOpenIDConnectProvider.
|
||||
private Response handleListOpenIDConnectProviders(MultivaluedMap<String, String> params) {
|
||||
var xml = new XmlBuilder().start("OpenIDConnectProviderList");
|
||||
XmlBuilder xml = new XmlBuilder().start("OpenIDConnectProviderList");
|
||||
for (OpenIDConnectProvider provider : iamService.listOpenIDConnectProviders()) {
|
||||
xml.start("member").elem("Arn", provider.getArn()).end("member");
|
||||
}
|
||||
@@ -607,7 +607,7 @@ public class IamQueryHandler {
|
||||
getMemberList(params, "ClientIDList"),
|
||||
getMemberList(params, "ThumbprintList"),
|
||||
extractTags(params, false));
|
||||
var xml = new XmlBuilder().elem("OpenIDConnectProviderArn", provider.getArn());
|
||||
XmlBuilder xml = new XmlBuilder().elem("OpenIDConnectProviderArn", provider.getArn());
|
||||
if (!provider.getTags().isEmpty()) {
|
||||
xml.start("Tags").raw(tagsXml(provider.getTags())).end("Tags");
|
||||
}
|
||||
@@ -619,7 +619,7 @@ public class IamQueryHandler {
|
||||
private Response handleGetOpenIDConnectProvider(MultivaluedMap<String, String> params) {
|
||||
OpenIDConnectProvider provider =
|
||||
iamService.getOpenIDConnectProvider(getParam(params, "OpenIDConnectProviderArn"));
|
||||
var xml = new XmlBuilder().elem("Url", provider.getUrl());
|
||||
XmlBuilder xml = new XmlBuilder().elem("Url", provider.getUrl());
|
||||
xml.start("ClientIDList");
|
||||
for (String clientId : provider.getClientIdList()) {
|
||||
xml.elem("member", clientId);
|
||||
@@ -699,7 +699,7 @@ public class IamQueryHandler {
|
||||
// ListAccountAliases is paginated on the wire (IsTruncated) even though an account can only
|
||||
// ever hold one alias, so the envelope carries the flag to match the AWS response shape.
|
||||
private Response handleListAccountAliases(MultivaluedMap<String, String> params) {
|
||||
var xml = new XmlBuilder().start("AccountAliases");
|
||||
XmlBuilder xml = new XmlBuilder().start("AccountAliases");
|
||||
iamService.getAccountAlias().ifPresent(alias -> xml.elem("member", alias));
|
||||
xml.end("AccountAliases").elem("IsTruncated", false);
|
||||
return Response.ok(AwsQueryResponse.envelope("ListAccountAliases", AwsNamespaces.IAM, xml.build())).build();
|
||||
@@ -755,7 +755,7 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private String passwordPolicyXml(AccountPasswordPolicy policy) {
|
||||
var xml = new XmlBuilder().start("PasswordPolicy")
|
||||
XmlBuilder xml = new XmlBuilder().start("PasswordPolicy")
|
||||
.elem("MinimumPasswordLength", policy.getMinimumPasswordLength())
|
||||
.elem("RequireSymbols", policy.isRequireSymbols())
|
||||
.elem("RequireNumbers", policy.isRequireNumbers())
|
||||
@@ -853,7 +853,7 @@ public class IamQueryHandler {
|
||||
return Stream.empty();
|
||||
}
|
||||
}).toList();
|
||||
var xml = new XmlBuilder()
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("Group").raw(groupXml(group)).end("Group")
|
||||
.start("Users");
|
||||
for (IamUser u : members) {
|
||||
@@ -876,7 +876,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListGroups(MultivaluedMap<String, String> params) {
|
||||
List<IamGroup> groupList = iamService.listGroups(getParam(params, "PathPrefix"));
|
||||
var xml = new XmlBuilder().start("Groups");
|
||||
XmlBuilder xml = new XmlBuilder().start("Groups");
|
||||
for (IamGroup g : groupList) {
|
||||
xml.start("member").raw(groupXml(g)).end("member");
|
||||
}
|
||||
@@ -896,7 +896,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListGroupsForUser(MultivaluedMap<String, String> params) {
|
||||
List<IamGroup> groupList = iamService.listGroupsForUser(getParam(params, "UserName"));
|
||||
var xml = new XmlBuilder().start("Groups");
|
||||
XmlBuilder xml = new XmlBuilder().start("Groups");
|
||||
for (IamGroup g : groupList) {
|
||||
xml.start("member").raw(groupXml(g)).end("member");
|
||||
}
|
||||
@@ -955,7 +955,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListRoles(MultivaluedMap<String, String> params) {
|
||||
List<IamRole> roleList = iamService.listRoles(getParam(params, "PathPrefix"));
|
||||
var xml = new XmlBuilder().start("Roles");
|
||||
XmlBuilder xml = new XmlBuilder().start("Roles");
|
||||
for (IamRole r : roleList) {
|
||||
xml.start("member").raw(roleXml(r, false)).end("member");
|
||||
}
|
||||
@@ -1022,7 +1022,7 @@ public class IamQueryHandler {
|
||||
private Response handleListPolicies(MultivaluedMap<String, String> params) {
|
||||
List<IamPolicy> policyList = iamService.listPolicies(
|
||||
getParam(params, "Scope"), getParam(params, "PathPrefix"));
|
||||
var xml = new XmlBuilder().start("Policies");
|
||||
XmlBuilder xml = new XmlBuilder().start("Policies");
|
||||
for (IamPolicy p : policyList) {
|
||||
xml.start("member").raw(policyXml(p, false)).end("member");
|
||||
}
|
||||
@@ -1032,7 +1032,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListEntitiesForPolicy(MultivaluedMap<String, String> params) {
|
||||
IamService.PolicyEntities entities = iamService.listEntitiesForPolicy(getParam(params, "PolicyArn"));
|
||||
var xml = new XmlBuilder().start("PolicyGroups");
|
||||
XmlBuilder xml = new XmlBuilder().start("PolicyGroups");
|
||||
for (IamGroup group : entities.groups()) {
|
||||
xml.start("member").elem("GroupName", group.getGroupName())
|
||||
.elem("GroupId", group.getGroupId()).end("member");
|
||||
@@ -1052,7 +1052,7 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private Response handleGetAccountSummary(MultivaluedMap<String, String> params) {
|
||||
var xml = new XmlBuilder().start("SummaryMap");
|
||||
XmlBuilder xml = new XmlBuilder().start("SummaryMap");
|
||||
for (Map.Entry<String, Long> entry : iamService.getAccountSummary().entrySet()) {
|
||||
xml.start("entry").elem("key", entry.getKey()).elem("value", entry.getValue()).end("entry");
|
||||
}
|
||||
@@ -1234,7 +1234,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListPolicyVersions(MultivaluedMap<String, String> params) {
|
||||
List<PolicyVersion> versions = iamService.listPolicyVersions(getParam(params, "PolicyArn"));
|
||||
var xml = new XmlBuilder().start("Versions");
|
||||
XmlBuilder xml = new XmlBuilder().start("Versions");
|
||||
for (PolicyVersion v : versions) {
|
||||
xml.start("member").raw(policyVersionXml(v)).end("member");
|
||||
}
|
||||
@@ -1437,7 +1437,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListAccessKeys(MultivaluedMap<String, String> params, String authorization) {
|
||||
List<AccessKey> keys = iamService.listAccessKeys(resolveUserName(params, authorization));
|
||||
var xml = new XmlBuilder().start("AccessKeyMetadata");
|
||||
XmlBuilder xml = new XmlBuilder().start("AccessKeyMetadata");
|
||||
for (AccessKey k : keys) {
|
||||
xml.start("member").raw(accessKeyXml(k, false)).end("member");
|
||||
}
|
||||
@@ -1540,7 +1540,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListInstanceProfiles(MultivaluedMap<String, String> params) {
|
||||
List<InstanceProfile> profiles = iamService.listInstanceProfiles(getParam(params, "PathPrefix"));
|
||||
var xml = new XmlBuilder().start("InstanceProfiles");
|
||||
XmlBuilder xml = new XmlBuilder().start("InstanceProfiles");
|
||||
for (InstanceProfile p : profiles) {
|
||||
// Documented listing subset: tags are omitted here, unlike GetInstanceProfile.
|
||||
xml.start("member").raw(instanceProfileXml(p, false)).end("member");
|
||||
@@ -1561,7 +1561,7 @@ public class IamQueryHandler {
|
||||
|
||||
private Response handleListInstanceProfilesForRole(MultivaluedMap<String, String> params) {
|
||||
List<InstanceProfile> profiles = iamService.listInstanceProfilesForRole(getParam(params, "RoleName"));
|
||||
var xml = new XmlBuilder().start("InstanceProfiles");
|
||||
XmlBuilder xml = new XmlBuilder().start("InstanceProfiles");
|
||||
for (InstanceProfile p : profiles) {
|
||||
xml.start("member").raw(instanceProfileXml(p, true)).end("member");
|
||||
}
|
||||
@@ -2215,7 +2215,7 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private String accessKeyXml(AccessKey k, boolean includeSecret) {
|
||||
var xml = new XmlBuilder()
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("UserName", k.getUserName())
|
||||
.elem("AccessKeyId", k.getAccessKeyId())
|
||||
.elem("Status", k.getStatus());
|
||||
@@ -2232,7 +2232,7 @@ public class IamQueryHandler {
|
||||
// and the InstanceProfileList embedded in GetAccountAuthorizationDetails's RoleDetail carry
|
||||
// no such note, so they stay detailed.
|
||||
private String instanceProfileXml(InstanceProfile p, boolean detailed) {
|
||||
var xml = new XmlBuilder()
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("InstanceProfileName", p.getInstanceProfileName())
|
||||
.elem("InstanceProfileId", p.getInstanceProfileId())
|
||||
.elem("Arn", p.getArn())
|
||||
@@ -2250,7 +2250,7 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private String attachedPoliciesXml(List<IamPolicy> policyList) {
|
||||
var xml = new XmlBuilder().start("AttachedPolicies");
|
||||
XmlBuilder xml = new XmlBuilder().start("AttachedPolicies");
|
||||
for (IamPolicy p : policyList) {
|
||||
xml.start("member")
|
||||
.elem("PolicyName", p.getPolicyName())
|
||||
@@ -2261,7 +2261,7 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private String inlinePolicyNamesXml(List<String> names) {
|
||||
var xml = new XmlBuilder().start("PolicyNames");
|
||||
XmlBuilder xml = new XmlBuilder().start("PolicyNames");
|
||||
for (String name : names) {
|
||||
xml.elem("member", name);
|
||||
}
|
||||
@@ -2285,8 +2285,8 @@ public class IamQueryHandler {
|
||||
}
|
||||
|
||||
private String tagsXml(Map<String, String> tags) {
|
||||
var xml = new XmlBuilder();
|
||||
for (var entry : tags.entrySet()) {
|
||||
XmlBuilder xml = new XmlBuilder();
|
||||
for (Map.Entry<String, String> entry : tags.entrySet()) {
|
||||
xml.start("member")
|
||||
.elem("Key", entry.getKey())
|
||||
.elem("Value", entry.getValue())
|
||||
|
||||
@@ -12,6 +12,7 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@@ -153,7 +154,7 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
}
|
||||
if (json.path("TableCreationParameters").hasNonNull("TableName")) {
|
||||
var tableName = json.path("TableCreationParameters").get("TableName").asText().trim();
|
||||
String tableName = json.path("TableCreationParameters").get("TableName").asText().trim();
|
||||
if (!tableName.isEmpty()) {
|
||||
return List.of(toDynamoDbTableArn(tableName, region, accountId));
|
||||
}
|
||||
@@ -183,14 +184,14 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
}
|
||||
if (json.hasNonNull("ImportArn")) {
|
||||
var importArn = json.get("ImportArn").asText().trim();
|
||||
String importArn = json.get("ImportArn").asText().trim();
|
||||
if (!importArn.isEmpty()) {
|
||||
return List.of(importArn);
|
||||
}
|
||||
}
|
||||
if (json.hasNonNull("RequestItems") && json.get("RequestItems").isObject()) {
|
||||
Set<String> arns = new LinkedHashSet<>();
|
||||
var fieldNames = json.get("RequestItems").fieldNames();
|
||||
Iterator<String> fieldNames = json.get("RequestItems").fieldNames();
|
||||
while (fieldNames.hasNext()) {
|
||||
String table = fieldNames.next().trim();
|
||||
if (!table.isEmpty()) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
|
||||
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
@@ -43,7 +44,7 @@ final class SAMLAssertionVerifier {
|
||||
static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException {
|
||||
try {
|
||||
byte[] bytes = Base64.getDecoder().decode(encoded);
|
||||
var document = SAMLXml.document(new String(bytes, java.nio.charset.StandardCharsets.UTF_8));
|
||||
Document document = SAMLXml.document(new String(bytes, StandardCharsets.UTF_8));
|
||||
Element assertion = document.getDocumentElement();
|
||||
if ("Response".equals(assertion.getLocalName())) {
|
||||
assertion = first(assertion, SAML, "Assertion");
|
||||
@@ -74,7 +75,7 @@ final class SAMLAssertionVerifier {
|
||||
}
|
||||
}
|
||||
X509Certificate certificate = certificate(provider.getCertificate());
|
||||
var context = new DOMValidateContext(certificate.getPublicKey(), signature);
|
||||
DOMValidateContext context = new DOMValidateContext(certificate.getPublicKey(), signature);
|
||||
context.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE);
|
||||
XMLSignature xmlSignature = XMLSignatureFactory.getInstance("DOM").unmarshalXMLSignature(context);
|
||||
if (xmlSignature.getSignedInfo().getReferences().size() != 1
|
||||
|
||||
@@ -9,12 +9,14 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Minimal IAM SAML provider registry used by STS assertion verification. */
|
||||
@@ -76,7 +78,7 @@ public class SAMLProviderService {
|
||||
}
|
||||
|
||||
public Optional<SAMLProvider> find(String arn) {
|
||||
var matcher = ARN.matcher(arn == null ? "" : arn);
|
||||
Matcher matcher = ARN.matcher(arn == null ? "" : arn);
|
||||
if (matcher.matches()) {
|
||||
return findForAccount(matcher.group(1), arn);
|
||||
}
|
||||
@@ -84,7 +86,7 @@ public class SAMLProviderService {
|
||||
}
|
||||
|
||||
public Optional<SAMLProvider> findForAccount(String accountId, String arn) {
|
||||
var matcher = ARN.matcher(arn == null ? "" : arn);
|
||||
Matcher matcher = ARN.matcher(arn == null ? "" : arn);
|
||||
if (!matcher.matches() || !matcher.group(1).equals(accountId)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -213,9 +215,9 @@ public class SAMLProviderService {
|
||||
record Parsed(String entityId, String certificateBase64) {}
|
||||
|
||||
static Parsed parse(String metadata) throws Exception {
|
||||
var doc = SAMLXml.document(metadata);
|
||||
var entity = doc.getDocumentElement().getAttribute("entityID");
|
||||
var cert = SAMLXml.text(doc, "X509Certificate");
|
||||
Document doc = SAMLXml.document(metadata);
|
||||
String entity = doc.getDocumentElement().getAttribute("entityID");
|
||||
String cert = SAMLXml.text(doc, "X509Certificate");
|
||||
if (entity == null || entity.isBlank() || cert == null || cert.isBlank()) {
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -54,15 +55,15 @@ public class SAMLTrustPolicyEvaluator {
|
||||
if (!condition.isObject()) {
|
||||
return false;
|
||||
}
|
||||
var operators = condition.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> operators = condition.fields();
|
||||
while (operators.hasNext()) {
|
||||
var operator = operators.next();
|
||||
Map.Entry<String, JsonNode> operator = operators.next();
|
||||
if (!operator.getValue().isObject()) {
|
||||
return false;
|
||||
}
|
||||
var entries = operator.getValue().fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
|
||||
while (entries.hasNext()) {
|
||||
var entry = entries.next();
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
String key = entry.getKey();
|
||||
int colon = key.indexOf(':');
|
||||
String claimName = colon < 0 ? key : key.substring(colon + 1);
|
||||
|
||||
+5
-4
@@ -7,6 +7,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -174,17 +175,17 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
return false;
|
||||
}
|
||||
|
||||
var operators = conditionNode.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> operators = conditionNode.fields();
|
||||
while (operators.hasNext()) {
|
||||
var operatorEntry = operators.next();
|
||||
Map.Entry<String, JsonNode> operatorEntry = operators.next();
|
||||
String operator = operatorEntry.getKey();
|
||||
JsonNode keys = operatorEntry.getValue();
|
||||
if (!keys.isObject()) {
|
||||
return false;
|
||||
}
|
||||
var keyIterator = keys.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> keyIterator = keys.fields();
|
||||
while (keyIterator.hasNext()) {
|
||||
var keyEntry = keyIterator.next();
|
||||
Map.Entry<String, JsonNode> keyEntry = keyIterator.next();
|
||||
if (!keySatisfied(operator, keyEntry.getKey(), keyEntry.getValue(),
|
||||
issuerKeyPrefix, claims)) {
|
||||
return false;
|
||||
|
||||
+10
-6
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.services.identitystore.model.Group;
|
||||
import io.github.hectorvent.floci.services.identitystore.model.Membership;
|
||||
import io.github.hectorvent.floci.services.identitystore.model.User;
|
||||
@@ -12,6 +13,9 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@ApplicationScoped
|
||||
public class IdentityStoreJsonHandler {
|
||||
private static final String ENTERPRISE_EXTENSION = "aws:identitystore:enterprise";
|
||||
@@ -60,7 +64,7 @@ public class IdentityStoreJsonHandler {
|
||||
}
|
||||
|
||||
private Response listGroups(JsonNode request) {
|
||||
var page = service.listGroups(request);
|
||||
PaginatedResult<Group> page = service.listGroups(request);
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
ArrayNode array = out.putArray("Groups");
|
||||
for (Group group : page.items()) {
|
||||
@@ -95,7 +99,7 @@ public class IdentityStoreJsonHandler {
|
||||
|
||||
private Response listUsers(JsonNode request) {
|
||||
boolean includeExtensions = includeExtensions(request);
|
||||
var page = service.listUsers(request);
|
||||
PaginatedResult<User> page = service.listUsers(request);
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
ArrayNode array = out.putArray("Users");
|
||||
for (User user : page.items()) {
|
||||
@@ -132,7 +136,7 @@ public class IdentityStoreJsonHandler {
|
||||
}
|
||||
|
||||
private Response listGroupMemberships(JsonNode request) {
|
||||
var page = service.listGroupMemberships(request);
|
||||
PaginatedResult<Membership> page = service.listGroupMemberships(request);
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
ArrayNode result = out.putArray("GroupMemberships");
|
||||
for (Membership membership : page.items()) {
|
||||
@@ -145,7 +149,7 @@ public class IdentityStoreJsonHandler {
|
||||
}
|
||||
|
||||
private Response listGroupMembershipsForMember(JsonNode request) {
|
||||
var page = service.listGroupMembershipsForMember(request);
|
||||
PaginatedResult<Membership> page = service.listGroupMembershipsForMember(request);
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
ArrayNode result = out.putArray("GroupMemberships");
|
||||
for (Membership membership : page.items()) {
|
||||
@@ -160,7 +164,7 @@ public class IdentityStoreJsonHandler {
|
||||
private Response isMemberInGroups(JsonNode request) {
|
||||
String storeId = IdentityStoreService.required(request, "IdentityStoreId");
|
||||
String userId = IdentityStoreService.memberUserId(request.get("MemberId"));
|
||||
var groupIds = service.validateGroupIds(request.get("GroupIds"));
|
||||
List<String> groupIds = service.validateGroupIds(request.get("GroupIds"));
|
||||
ObjectNode out = mapper.createObjectNode();
|
||||
ArrayNode results = out.putArray("Results");
|
||||
for (String groupId : groupIds) {
|
||||
@@ -238,7 +242,7 @@ public class IdentityStoreJsonHandler {
|
||||
|
||||
private static void putTimestamp(ObjectNode target, String field, String timestamp) {
|
||||
if (timestamp != null) {
|
||||
var instant = java.time.Instant.parse(timestamp);
|
||||
Instant instant = Instant.parse(timestamp);
|
||||
double unixTimestamp = instant.getEpochSecond() + instant.getNano() / 1_000_000_000.0;
|
||||
target.put(field, unixTimestamp);
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import jakarta.ws.rs.core.UriInfo;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Base64;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -738,7 +739,7 @@ public class ScimController {
|
||||
ArrayNode targetArray = target.putArray(targetField);
|
||||
for (JsonNode item : array) {
|
||||
ObjectNode targetItem = targetArray.addObject();
|
||||
for (var field : fields.entrySet()) {
|
||||
for (Map.Entry<String, String> field : fields.entrySet()) {
|
||||
JsonNode value = item.get(field.getKey());
|
||||
if (value != null && !value.isNull()) {
|
||||
targetItem.set(field.getValue(), value.deepCopy());
|
||||
@@ -756,7 +757,7 @@ public class ScimController {
|
||||
ArrayNode targetArray = target.putArray(targetField);
|
||||
for (JsonNode item : array) {
|
||||
ObjectNode targetItem = targetArray.addObject();
|
||||
for (var field : fields.entrySet()) {
|
||||
for (Map.Entry<String, String> field : fields.entrySet()) {
|
||||
JsonNode value = item.get(field.getKey());
|
||||
if (value != null && !value.isNull()) {
|
||||
targetItem.set(field.getValue(), value.deepCopy());
|
||||
@@ -805,9 +806,9 @@ public class ScimController {
|
||||
if (!value.isObject() || value.isEmpty()) {
|
||||
throw validation("A patch operation without path must provide an object value.");
|
||||
}
|
||||
var fields = value.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = value.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
validatePatchUserAttribute(identityStoreId, userId, op, entry.getKey(), entry.getValue());
|
||||
if ("userName".equals(entry.getKey())) {
|
||||
userNameChanges++;
|
||||
@@ -914,9 +915,9 @@ public class ScimController {
|
||||
String path = optionalText(operation, "path");
|
||||
JsonNode value = operation.get("value");
|
||||
if (path == null) {
|
||||
var fields = value.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = value.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
applyPatchUserAttribute(identityStoreId, userId, op, entry.getKey(), entry.getValue());
|
||||
}
|
||||
} else {
|
||||
|
||||
+20
-16
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.inspector2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -18,6 +20,8 @@ import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@@ -50,8 +54,8 @@ public class Inspector2Controller {
|
||||
throw new AwsException("ValidationException", "nextToken is invalid.", 400);
|
||||
}
|
||||
InspectorState state = service.delegatedAdminState(region(headers), requestContext.getAccountId());
|
||||
var response = objectMapper.createObjectNode();
|
||||
var accounts = response.putArray("delegatedAdminAccounts");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode accounts = response.putArray("delegatedAdminAccounts");
|
||||
if (state.getAdminAccountId() != null) {
|
||||
accounts.addObject().put("accountId", state.getAdminAccountId()).put("status", "ENABLED");
|
||||
}
|
||||
@@ -64,7 +68,7 @@ public class Inspector2Controller {
|
||||
JsonNode request = parse(body);
|
||||
String accountId = request.path("delegatedAdminAccountId").asText(null);
|
||||
service.enableDelegatedAdmin(region(headers), requestContext.getAccountId(), accountId);
|
||||
var response = objectMapper.createObjectNode();
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("delegatedAdminAccountId", accountId);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
@@ -75,7 +79,7 @@ public class Inspector2Controller {
|
||||
JsonNode request = parse(body);
|
||||
String accountId = request.path("delegatedAdminAccountId").asText(null);
|
||||
service.disableDelegatedAdmin(region(headers), requestContext.getAccountId(), accountId);
|
||||
var response = objectMapper.createObjectNode();
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("delegatedAdminAccountId", accountId);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
@@ -90,12 +94,12 @@ public class Inspector2Controller {
|
||||
"accountIds must contain at most 100 account IDs.", 400);
|
||||
}
|
||||
java.util.List<String> requestedAccounts = requestedAccounts(accountIds);
|
||||
var response = objectMapper.createObjectNode();
|
||||
var accounts = response.putArray("accounts");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode accounts = response.putArray("accounts");
|
||||
for (String accountId : requestedAccounts) {
|
||||
InspectorState state = service.accountStatus(
|
||||
region(headers), requestContext.getAccountId(), accountId);
|
||||
var account = accounts.addObject();
|
||||
ObjectNode account = accounts.addObject();
|
||||
account.put("accountId", accountId);
|
||||
account.set("state", stateNode(state.getStatus()));
|
||||
account.set("resourceState", resourceState(state));
|
||||
@@ -108,11 +112,11 @@ public class Inspector2Controller {
|
||||
@Path("/enable")
|
||||
public Response enable(@Context HttpHeaders headers, String body) {
|
||||
JsonNode request = parse(body);
|
||||
var enabled = service.enable(region(headers), requestContext.getAccountId(), request);
|
||||
var response = objectMapper.createObjectNode();
|
||||
var accounts = response.putArray("accounts");
|
||||
Map<String, InspectorState> enabled = service.enable(region(headers), requestContext.getAccountId(), request);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode accounts = response.putArray("accounts");
|
||||
enabled.forEach((accountId, state) -> {
|
||||
var account = accounts.addObject();
|
||||
ObjectNode account = accounts.addObject();
|
||||
account.put("accountId", accountId);
|
||||
account.put("status", state.getStatus());
|
||||
account.set("resourceStatus", resourceStatus(state));
|
||||
@@ -137,8 +141,8 @@ public class Inspector2Controller {
|
||||
}
|
||||
|
||||
private com.fasterxml.jackson.databind.node.ObjectNode organizationConfigurationResponse(InspectorState state) {
|
||||
var response = objectMapper.createObjectNode();
|
||||
var autoEnable = response.putObject("autoEnable");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode autoEnable = response.putObject("autoEnable");
|
||||
autoEnable.put("ec2", state.isAutoEnableEc2());
|
||||
autoEnable.put("ecr", state.isAutoEnableEcr());
|
||||
autoEnable.put("lambda", state.isAutoEnableLambda());
|
||||
@@ -161,7 +165,7 @@ public class Inspector2Controller {
|
||||
}
|
||||
|
||||
private com.fasterxml.jackson.databind.node.ObjectNode resourceState(InspectorState state) {
|
||||
var resources = objectMapper.createObjectNode();
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
resources.set("ec2", stateNode(state.getEc2Status()));
|
||||
resources.set("ecr", stateNode(state.getEcrStatus()));
|
||||
resources.set("lambda", stateNode(state.getLambdaStatus()));
|
||||
@@ -171,7 +175,7 @@ public class Inspector2Controller {
|
||||
}
|
||||
|
||||
private com.fasterxml.jackson.databind.node.ObjectNode resourceStatus(InspectorState state) {
|
||||
var resources = objectMapper.createObjectNode();
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
resources.put("ec2", state.getEc2Status());
|
||||
resources.put("ecr", state.getEcrStatus());
|
||||
resources.put("lambda", state.getLambdaStatus());
|
||||
@@ -181,7 +185,7 @@ public class Inspector2Controller {
|
||||
}
|
||||
|
||||
private com.fasterxml.jackson.databind.node.ObjectNode stateNode(String status) {
|
||||
var state = objectMapper.createObjectNode();
|
||||
ObjectNode state = objectMapper.createObjectNode();
|
||||
state.put("status", status);
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -76,7 +77,7 @@ public class IotDataController {
|
||||
public Response listNamedShadowsForThing(@Context HttpHeaders headers,
|
||||
@PathParam("thingName") String thingName) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var results = response.putArray("results");
|
||||
ArrayNode results = response.putArray("results");
|
||||
iotService.listNamedShadowsForThing(thingName, regionResolver.resolveRegion(headers)).forEach(results::add);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
@@ -112,7 +113,7 @@ public class IotDataController {
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
IotService.Page<String> page = iotService.listSubscriptions(clientId, maxResults, nextToken);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var subscriptions = response.putArray("subscriptions");
|
||||
ArrayNode subscriptions = response.putArray("subscriptions");
|
||||
for (String topicFilter : page.items()) {
|
||||
ObjectNode subscription = subscriptions.addObject();
|
||||
subscription.put("topicFilter", topicFilter);
|
||||
@@ -172,7 +173,7 @@ public class IotDataController {
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
IotService.Page<IotRetainedMessage> page = iotService.listRetainedMessages(maxResults, nextToken);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var topics = response.putArray("retainedTopics");
|
||||
ArrayNode topics = response.putArray("retainedTopics");
|
||||
for (IotRetainedMessage retained : page.items()) {
|
||||
ObjectNode item = topics.addObject();
|
||||
item.put("topic", retained.getTopic());
|
||||
|
||||
@@ -314,7 +314,7 @@ public class KinesisJsonHandler {
|
||||
private Response handleRegisterStreamConsumer(JsonNode request, String region) {
|
||||
String streamArn = request.path("StreamARN").asText();
|
||||
String consumerName = request.path("ConsumerName").asText();
|
||||
var consumer = service.registerStreamConsumer(streamArn, consumerName, region);
|
||||
KinesisConsumer consumer = service.registerStreamConsumer(streamArn, consumerName, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("Consumer", consumerToNode(consumer));
|
||||
return Response.ok(response).build();
|
||||
@@ -332,7 +332,7 @@ public class KinesisJsonHandler {
|
||||
String streamArn = request.has("StreamARN") ? request.path("StreamARN").asText() : null;
|
||||
String consumerName = request.has("ConsumerName") ? request.path("ConsumerName").asText() : null;
|
||||
String consumerArn = request.has("ConsumerARN") ? request.path("ConsumerARN").asText() : null;
|
||||
var consumer = service.describeStreamConsumer(streamArn, consumerName, consumerArn, region);
|
||||
KinesisConsumer consumer = service.describeStreamConsumer(streamArn, consumerName, consumerArn, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("ConsumerDescription", consumerToNode(consumer));
|
||||
return Response.ok(response).build();
|
||||
@@ -340,7 +340,7 @@ public class KinesisJsonHandler {
|
||||
|
||||
private Response handleListStreamConsumers(JsonNode request, String region) {
|
||||
String streamArn = request.path("StreamARN").asText();
|
||||
var consumers = service.listStreamConsumers(streamArn, region);
|
||||
List<KinesisConsumer> consumers = service.listStreamConsumers(streamArn, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode array = response.putArray("Consumers");
|
||||
consumers.forEach(c -> array.add(consumerToNode(c)));
|
||||
|
||||
+2
-2
@@ -177,9 +177,9 @@ public class FlinkRestClient {
|
||||
if (resp.statusCode() != 200) {
|
||||
return null;
|
||||
}
|
||||
var root = mapper.readTree(resp.body());
|
||||
JsonNode root = mapper.readTree(resp.body());
|
||||
String statusId = root.path("status").path("id").asText(null);
|
||||
var operation = root.path("operation");
|
||||
JsonNode operation = root.path("operation");
|
||||
boolean failed = operation.has("failure-cause");
|
||||
String location = operation.path("location").asText(null);
|
||||
return new SavepointStatus(statusId, location, failed);
|
||||
|
||||
@@ -67,7 +67,7 @@ public class EsmStore {
|
||||
|
||||
public List<EventSourceMapping> listByFunction(String functionKey) {
|
||||
return backend.scan(k -> {
|
||||
var esm = backend.get(k).orElse(null);
|
||||
EventSourceMapping esm = backend.get(k).orElse(null);
|
||||
if (esm == null) return false;
|
||||
// Match by full ARN or by short function name
|
||||
return functionKey.equals(esm.getFunctionArn()) || functionKey.equals(esm.getFunctionName());
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.lambda;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
@@ -200,7 +201,7 @@ public class KinesisEventSourcePoller implements Resettable {
|
||||
|
||||
private String buildKinesisEvent(List<KinesisRecord> records, EventSourceMapping esm, String shardId) {
|
||||
try {
|
||||
var recordsArray = objectMapper.createArrayNode();
|
||||
ArrayNode recordsArray = objectMapper.createArrayNode();
|
||||
for (KinesisRecord rec : records) {
|
||||
ObjectNode kinesisNode = objectMapper.createObjectNode();
|
||||
kinesisNode.put("kinesisSchemaVersion", "1.0");
|
||||
|
||||
@@ -204,13 +204,13 @@ public class LambdaLayerController {
|
||||
* by a non-default account resolves the default-account bucket and 404s.
|
||||
*/
|
||||
private String tasksLocation(LambdaLayerVersion lv, String region, UriInfo uriInfo) {
|
||||
var base = uriInfo.getBaseUri().toString();
|
||||
String base = uriInfo.getBaseUri().toString();
|
||||
if (base.endsWith("/")) {
|
||||
base = base.substring(0, base.length() - 1);
|
||||
}
|
||||
var account = AwsArnUtils.accountOrDefault(lv.getLayerVersionArn(), "000000000000");
|
||||
var bucket = LambdaService.tasksBucketName(region);
|
||||
var key = LambdaService.layerObjectKey(account, lv.getLayerName(), lv.getVersion());
|
||||
String account = AwsArnUtils.accountOrDefault(lv.getLayerVersionArn(), "000000000000");
|
||||
String bucket = LambdaService.tasksBucketName(region);
|
||||
String key = LambdaService.layerObjectKey(account, lv.getLayerName(), lv.getVersion());
|
||||
return base + "/" + LambdaService.encodeObjectPath(bucket)
|
||||
+ "/" + LambdaService.encodeObjectPath(key)
|
||||
+ "?X-Amz-Credential=" + account + "%2F00010101%2F" + region + "%2Fs3%2Faws4_request";
|
||||
|
||||
@@ -432,7 +432,7 @@ public class LambdaLayerService {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
var account = AwsArnUtils.accountOrDefault(lv.getLayerVersionArn(), "000000000000");
|
||||
String account = AwsArnUtils.accountOrDefault(lv.getLayerVersionArn(), "000000000000");
|
||||
s3Service.deleteObject(LambdaService.tasksBucketName(region),
|
||||
LambdaService.layerObjectKey(account, lv.getLayerName(), lv.getVersion()));
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
@@ -377,7 +378,7 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
}
|
||||
Set<String> receivedIds = received.stream().map(Message::getMessageId).collect(Collectors.toSet());
|
||||
try {
|
||||
var failures = objectMapper.readTree(result.getPayload()).get("batchItemFailures");
|
||||
JsonNode failures = objectMapper.readTree(result.getPayload()).get("batchItemFailures");
|
||||
if (failures == null || failures.isNull()) {
|
||||
return Set.of();
|
||||
}
|
||||
@@ -385,8 +386,8 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
return failWholeBatch(esm, receivedIds, "batchItemFailures is not an array");
|
||||
}
|
||||
Set<String> failedIds = new HashSet<>();
|
||||
for (var item : failures) {
|
||||
var id = item.get("itemIdentifier");
|
||||
for (JsonNode item : failures) {
|
||||
JsonNode id = item.get("itemIdentifier");
|
||||
if (id == null || id.isNull() || id.asText().isEmpty()) {
|
||||
return failWholeBatch(esm, receivedIds, "entry has a missing, null or empty itemIdentifier");
|
||||
}
|
||||
@@ -410,7 +411,7 @@ public class SqsEventSourcePoller implements Resettable {
|
||||
|
||||
String buildSqsEvent(List<Message> messages, EventSourceMapping esm) {
|
||||
try {
|
||||
var records = objectMapper.createArrayNode();
|
||||
ArrayNode records = objectMapper.createArrayNode();
|
||||
for (Message msg : messages) {
|
||||
records.add(buildSqsRecordNode(msg, esm));
|
||||
}
|
||||
|
||||
+2
-2
@@ -43,7 +43,7 @@ public class LambdaRuntimeLauncherProducer {
|
||||
LambdaRuntimeLauncher launcher(EmulatorConfig config,
|
||||
Instance<ContainerLauncher> docker,
|
||||
Instance<KubernetesPodLauncher> kubernetes) {
|
||||
var executor = requireValidExecutor(config);
|
||||
String executor = requireValidExecutor(config);
|
||||
if (executor.equals("kubernetes")) {
|
||||
LOG.info("Lambda executor: kubernetes (environments run as pods)");
|
||||
return kubernetes.get();
|
||||
@@ -52,7 +52,7 @@ public class LambdaRuntimeLauncherProducer {
|
||||
}
|
||||
|
||||
private static String requireValidExecutor(EmulatorConfig config) {
|
||||
var executor = config.services().lambda().executor().trim().toLowerCase(Locale.ROOT);
|
||||
String executor = config.services().lambda().executor().trim().toLowerCase(Locale.ROOT);
|
||||
if (!executor.equals("docker") && !executor.equals("kubernetes")) {
|
||||
throw new IllegalArgumentException(
|
||||
"Unknown floci.services.lambda.executor '" + executor
|
||||
|
||||
+59
-59
@@ -94,9 +94,9 @@ final class EksTokenMinter {
|
||||
if (!isAwsEksGetToken(exec)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
var execEnv = execEnv(exec);
|
||||
Map<String, String> execEnv = execEnv(exec);
|
||||
UnaryOperator<String> env = name -> execEnv.getOrDefault(name, System.getenv(name));
|
||||
var args = parseArgs(exec, env);
|
||||
ExecArgs args = parseArgs(exec, env);
|
||||
return Optional.of(new CachingTokenSupplier(args.clusterName(), args.region(), execEnv));
|
||||
}
|
||||
|
||||
@@ -109,14 +109,14 @@ final class EksTokenMinter {
|
||||
* profile-scoped kubeconfig silently resolves the wrong AWS identity.
|
||||
*/
|
||||
private static Map<String, String> execEnv(JsonNode exec) {
|
||||
var envNode = exec.path("env");
|
||||
JsonNode envNode = exec.path("env");
|
||||
if (!envNode.isArray()) {
|
||||
return Map.of();
|
||||
}
|
||||
var result = new LinkedHashMap<String, String>();
|
||||
for (var entry : envNode) {
|
||||
var name = entry.path("name").asText(null);
|
||||
var value = entry.path("value").asText(null);
|
||||
LinkedHashMap<String, String> result = new LinkedHashMap<>();
|
||||
for (JsonNode entry : envNode) {
|
||||
String name = entry.path("name").asText(null);
|
||||
String value = entry.path("value").asText(null);
|
||||
if (name != null && value != null) {
|
||||
result.put(name, value);
|
||||
}
|
||||
@@ -125,12 +125,12 @@ final class EksTokenMinter {
|
||||
}
|
||||
|
||||
static boolean isAwsEksGetToken(JsonNode exec) {
|
||||
var command = exec.path("command").asText("");
|
||||
String command = exec.path("command").asText("");
|
||||
if (command.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
var fileName = Path.of(command).getFileName();
|
||||
var commandName = fileName == null ? command : fileName.toString();
|
||||
Path fileName = Path.of(command).getFileName();
|
||||
String commandName = fileName == null ? command : fileName.toString();
|
||||
if (!"aws".equals(commandName)) { // partition-literal: kubeconfig exec command
|
||||
return false;
|
||||
}
|
||||
@@ -148,7 +148,7 @@ final class EksTokenMinter {
|
||||
if (!args.isArray()) {
|
||||
return -1;
|
||||
}
|
||||
for (var i = 0; i + 1 < args.size(); i++) {
|
||||
for (int i = 0; i + 1 < args.size(); i++) {
|
||||
if ("eks".equals(args.get(i).asText()) && "get-token".equals(args.get(i + 1).asText())) {
|
||||
return i;
|
||||
}
|
||||
@@ -165,15 +165,15 @@ final class EksTokenMinter {
|
||||
* the region fallback is deterministically testable regardless of the host's own environment.
|
||||
*/
|
||||
static ExecArgs parseArgs(JsonNode exec, UnaryOperator<String> env) {
|
||||
var args = exec.path("args");
|
||||
var subcommandIndex = findSubcommandIndex(args);
|
||||
JsonNode args = exec.path("args");
|
||||
int subcommandIndex = findSubcommandIndex(args);
|
||||
String clusterName = null;
|
||||
String region = null;
|
||||
for (var i = 0; i < args.size(); i++) {
|
||||
for (int i = 0; i < args.size(); i++) {
|
||||
if (i == subcommandIndex || i == subcommandIndex + 1) {
|
||||
continue;
|
||||
}
|
||||
var arg = args.get(i).asText();
|
||||
String arg = args.get(i).asText();
|
||||
if (isRoleOption(arg)) {
|
||||
throw new IllegalStateException(
|
||||
"kubeconfig exec plugin 'aws eks get-token --role-arn' is not supported: the "
|
||||
@@ -182,7 +182,7 @@ final class EksTokenMinter {
|
||||
+ "that already have cluster access.");
|
||||
}
|
||||
if (("--cluster-name".equals(arg) || "--region".equals(arg)) && i + 1 < args.size()) {
|
||||
var value = args.get(++i).asText();
|
||||
String value = args.get(++i).asText();
|
||||
if ("--cluster-name".equals(arg)) {
|
||||
clusterName = value;
|
||||
} else {
|
||||
@@ -222,7 +222,7 @@ final class EksTokenMinter {
|
||||
* with or without a {@code --flag=value} suffix, is rejected explicitly.
|
||||
*/
|
||||
private static boolean isRoleOption(String arg) {
|
||||
var name = arg.split("=", 2)[0];
|
||||
String name = arg.split("=", 2)[0];
|
||||
return name.length() >= "--role".length() && "--role-arn".startsWith(name);
|
||||
}
|
||||
|
||||
@@ -241,7 +241,7 @@ final class EksTokenMinter {
|
||||
|
||||
@Override
|
||||
public synchronized String get() {
|
||||
var now = Instant.now();
|
||||
Instant now = Instant.now();
|
||||
if (token == null || !now.isBefore(expiresAt.minusSeconds(REFRESH_MARGIN_SECONDS))) {
|
||||
token = mint(clusterName, region, execEnv);
|
||||
expiresAt = now.plusSeconds(TOKEN_VALIDITY_SECONDS);
|
||||
@@ -265,14 +265,14 @@ final class EksTokenMinter {
|
||||
* can only ever be checked for shape, never against a hard-coded expected value.
|
||||
*/
|
||||
static String mint(String clusterName, String region, AwsCredentials credentials, Clock clock) {
|
||||
var now = clock.instant();
|
||||
var amzDate = AMZ_DATE.format(now);
|
||||
var dateStamp = AMZ_DATE_STAMP.format(now);
|
||||
var host = stsHost(region);
|
||||
var credentialScope = dateStamp + "/" + region + "/sts/aws4_request";
|
||||
var signedHeaders = "host;" + CLUSTER_ID_HEADER;
|
||||
Instant now = clock.instant();
|
||||
String amzDate = AMZ_DATE.format(now);
|
||||
String dateStamp = AMZ_DATE_STAMP.format(now);
|
||||
String host = stsHost(region);
|
||||
String credentialScope = dateStamp + "/" + region + "/sts/aws4_request";
|
||||
String signedHeaders = "host;" + CLUSTER_ID_HEADER;
|
||||
|
||||
var queryParams = new TreeMap<String, String>();
|
||||
TreeMap<String, String> queryParams = new TreeMap<>();
|
||||
queryParams.put("Action", "GetCallerIdentity");
|
||||
queryParams.put("Version", "2011-06-15");
|
||||
queryParams.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
|
||||
@@ -284,21 +284,21 @@ final class EksTokenMinter {
|
||||
queryParams.put("X-Amz-Security-Token", credentials.sessionToken());
|
||||
}
|
||||
|
||||
var canonicalQueryString = queryParams.entrySet().stream()
|
||||
String canonicalQueryString = queryParams.entrySet().stream()
|
||||
.map(e -> uriEncode(e.getKey()) + "=" + uriEncode(e.getValue()))
|
||||
.collect(Collectors.joining("&"));
|
||||
|
||||
// Sorted by header name ("host" < "x-k8s-aws-id"), matching X-Amz-SignedHeaders above.
|
||||
var canonicalHeaders = "host:" + host + "\n" + CLUSTER_ID_HEADER + ":" + clusterName + "\n";
|
||||
var canonicalRequest = "GET\n/\n" + canonicalQueryString + "\n"
|
||||
String canonicalHeaders = "host:" + host + "\n" + CLUSTER_ID_HEADER + ":" + clusterName + "\n";
|
||||
String canonicalRequest = "GET\n/\n" + canonicalQueryString + "\n"
|
||||
+ canonicalHeaders + "\n" + signedHeaders + "\n" + EMPTY_BODY_SHA256;
|
||||
|
||||
var stringToSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
|
||||
String stringToSign = "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n"
|
||||
+ sha256Hex(canonicalRequest);
|
||||
var signingKey = deriveSigningKey(credentials.secretAccessKey(), dateStamp, region, "sts");
|
||||
var signature = hexEncode(hmacSha256(signingKey, stringToSign));
|
||||
byte[] signingKey = deriveSigningKey(credentials.secretAccessKey(), dateStamp, region, "sts");
|
||||
String signature = hexEncode(hmacSha256(signingKey, stringToSign));
|
||||
|
||||
var url = "https://" + host + "/?" + canonicalQueryString + "&X-Amz-Signature=" + signature;
|
||||
String url = "https://" + host + "/?" + canonicalQueryString + "&X-Amz-Signature=" + signature;
|
||||
return TOKEN_PREFIX + Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(url.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
@@ -344,8 +344,8 @@ final class EksTokenMinter {
|
||||
// execEnv has neither key at this point (the check above already rejected exactly one
|
||||
// being present), so these are necessarily ambient-sourced; the session token must be
|
||||
// too, for the same reason as the exec.env branch above.
|
||||
var accessKeyId = ambientEnv.apply("AWS_ACCESS_KEY_ID");
|
||||
var secretAccessKey = ambientEnv.apply("AWS_SECRET_ACCESS_KEY");
|
||||
String accessKeyId = ambientEnv.apply("AWS_ACCESS_KEY_ID");
|
||||
String secretAccessKey = ambientEnv.apply("AWS_SECRET_ACCESS_KEY");
|
||||
if (hasPairedKeys("the environment", accessKeyId, secretAccessKey)) {
|
||||
return new AwsCredentials(accessKeyId, secretAccessKey, ambientEnv.apply("AWS_SESSION_TOKEN"));
|
||||
}
|
||||
@@ -361,8 +361,8 @@ final class EksTokenMinter {
|
||||
* intended to supply.
|
||||
*/
|
||||
private static boolean hasPairedKeys(String source, String accessKeyId, String secretAccessKey) {
|
||||
var hasAccessKeyId = accessKeyId != null && !accessKeyId.isBlank();
|
||||
var hasSecretAccessKey = secretAccessKey != null && !secretAccessKey.isBlank();
|
||||
boolean hasAccessKeyId = accessKeyId != null && !accessKeyId.isBlank();
|
||||
boolean hasSecretAccessKey = secretAccessKey != null && !secretAccessKey.isBlank();
|
||||
if (hasAccessKeyId != hasSecretAccessKey) {
|
||||
throw new IllegalStateException(
|
||||
"Partial AWS credentials in " + source + ": "
|
||||
@@ -374,8 +374,8 @@ final class EksTokenMinter {
|
||||
}
|
||||
|
||||
private static AwsCredentials resolveFromSharedCredentialsFile(UnaryOperator<String> env, String profileEnv) {
|
||||
var pathValue = env.apply("AWS_SHARED_CREDENTIALS_FILE");
|
||||
var path = (pathValue != null && !pathValue.isBlank())
|
||||
String pathValue = env.apply("AWS_SHARED_CREDENTIALS_FILE");
|
||||
Path path = (pathValue != null && !pathValue.isBlank())
|
||||
? Path.of(pathValue)
|
||||
: Path.of(System.getProperty("user.home"), ".aws", "credentials");
|
||||
if (!Files.exists(path)) {
|
||||
@@ -385,10 +385,10 @@ final class EksTokenMinter {
|
||||
+ path + ". Set AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, or "
|
||||
+ "AWS_SHARED_CREDENTIALS_FILE.");
|
||||
}
|
||||
var profile = (profileEnv == null || profileEnv.isBlank()) ? "default" : profileEnv;
|
||||
var section = readIniSection(path, profile);
|
||||
var accessKeyId = section.get("aws_access_key_id");
|
||||
var secretAccessKey = section.get("aws_secret_access_key");
|
||||
String profile = (profileEnv == null || profileEnv.isBlank()) ? "default" : profileEnv;
|
||||
Map<String, String> section = readIniSection(path, profile);
|
||||
String accessKeyId = section.get("aws_access_key_id");
|
||||
String secretAccessKey = section.get("aws_secret_access_key");
|
||||
if (accessKeyId == null || secretAccessKey == null) {
|
||||
throw new IllegalStateException(
|
||||
"AWS credentials profile '" + profile + "' in " + path
|
||||
@@ -398,12 +398,12 @@ final class EksTokenMinter {
|
||||
}
|
||||
|
||||
private static Map<String, String> readIniSection(Path path, String profile) {
|
||||
var target = "[" + profile + "]";
|
||||
var result = new LinkedHashMap<String, String>();
|
||||
String target = "[" + profile + "]";
|
||||
LinkedHashMap<String, String> result = new LinkedHashMap<>();
|
||||
try {
|
||||
var inSection = false;
|
||||
for (var raw : Files.readAllLines(path, StandardCharsets.UTF_8)) {
|
||||
var line = raw.strip();
|
||||
boolean inSection = false;
|
||||
for (String raw : Files.readAllLines(path, StandardCharsets.UTF_8)) {
|
||||
String line = raw.strip();
|
||||
if (line.isEmpty() || line.startsWith("#") || line.startsWith(";")) {
|
||||
continue;
|
||||
}
|
||||
@@ -414,7 +414,7 @@ final class EksTokenMinter {
|
||||
if (!inSection) {
|
||||
continue;
|
||||
}
|
||||
var eq = line.indexOf('=');
|
||||
int eq = line.indexOf('=');
|
||||
if (eq > 0) {
|
||||
result.put(line.substring(0, eq).strip(), line.substring(eq + 1).strip());
|
||||
}
|
||||
@@ -430,9 +430,9 @@ final class EksTokenMinter {
|
||||
|
||||
/** RFC 3986 percent-encoding, byte-wise over UTF-8, per the SigV4 spec (not {@link java.net.URLEncoder}). */
|
||||
private static String uriEncode(String input) {
|
||||
var result = new StringBuilder();
|
||||
for (var b : input.getBytes(StandardCharsets.UTF_8)) {
|
||||
var c = (char) (b & 0xFF);
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (byte b : input.getBytes(StandardCharsets.UTF_8)) {
|
||||
char c = (char) (b & 0xFF);
|
||||
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
|
||||
|| c == '-' || c == '_' || c == '.' || c == '~') {
|
||||
result.append(c);
|
||||
@@ -444,16 +444,16 @@ final class EksTokenMinter {
|
||||
}
|
||||
|
||||
private static byte[] deriveSigningKey(String secretKey, String date, String region, String service) {
|
||||
var kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
|
||||
var kDate = hmacSha256(kSecret, date);
|
||||
var kRegion = hmacSha256(kDate, region);
|
||||
var kService = hmacSha256(kRegion, service);
|
||||
byte[] kSecret = ("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8);
|
||||
byte[] kDate = hmacSha256(kSecret, date);
|
||||
byte[] kRegion = hmacSha256(kDate, region);
|
||||
byte[] kService = hmacSha256(kRegion, service);
|
||||
return hmacSha256(kService, "aws4_request");
|
||||
}
|
||||
|
||||
private static byte[] hmacSha256(byte[] key, String data) {
|
||||
try {
|
||||
var mac = Mac.getInstance("HmacSHA256");
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key, "HmacSHA256"));
|
||||
return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (GeneralSecurityException e) {
|
||||
@@ -463,7 +463,7 @@ final class EksTokenMinter {
|
||||
|
||||
private static String sha256Hex(String input) {
|
||||
try {
|
||||
var digest = MessageDigest.getInstance("SHA-256");
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return hexEncode(digest.digest(input.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("Could not compute SHA-256: " + e.getMessage(), e);
|
||||
@@ -471,8 +471,8 @@ final class EksTokenMinter {
|
||||
}
|
||||
|
||||
private static String hexEncode(byte[] bytes) {
|
||||
var sb = new StringBuilder(bytes.length * 2);
|
||||
for (var b : bytes) {
|
||||
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
|
||||
+55
-54
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.Collection;
|
||||
import javax.net.ssl.KeyManager;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
@@ -127,11 +128,11 @@ public class KubernetesApiClient {
|
||||
}
|
||||
|
||||
public List<JsonNode> listPods(String namespace, Map<String, String> labelSelector) {
|
||||
var selector = labelSelector.entrySet().stream()
|
||||
String selector = labelSelector.entrySet().stream()
|
||||
.map(e -> e.getKey() + "=" + e.getValue())
|
||||
.collect(Collectors.joining(","));
|
||||
var path = podsPath(namespace) + "?labelSelector=" + URLEncoder.encode(selector, StandardCharsets.UTF_8);
|
||||
var items = new ArrayList<JsonNode>();
|
||||
String path = podsPath(namespace) + "?labelSelector=" + URLEncoder.encode(selector, StandardCharsets.UTF_8);
|
||||
ArrayList<JsonNode> items = new ArrayList<>();
|
||||
send("GET", path, null, 200).path("items").forEach(items::add);
|
||||
return items;
|
||||
}
|
||||
@@ -155,9 +156,9 @@ public class KubernetesApiClient {
|
||||
* @throws IllegalStateException if {@code condition} is not satisfied within {@code timeoutSeconds}
|
||||
*/
|
||||
public JsonNode waitForPod(String namespace, String name, Predicate<JsonNode> condition, int timeoutSeconds) {
|
||||
var deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
|
||||
while (true) {
|
||||
var pod = getPod(namespace, name).orElse(null);
|
||||
JsonNode pod = getPod(namespace, name).orElse(null);
|
||||
if (condition.test(pod)) {
|
||||
return pod;
|
||||
}
|
||||
@@ -184,8 +185,8 @@ public class KubernetesApiClient {
|
||||
if (e.getStatusCode() != 409) {
|
||||
throw e;
|
||||
}
|
||||
var name = configMap.path("metadata").path("name").asText();
|
||||
var existing = getOptional(configMapPath(namespace, name)).orElseThrow(() -> e);
|
||||
String name = configMap.path("metadata").path("name").asText();
|
||||
JsonNode existing = getOptional(configMapPath(namespace, name)).orElseThrow(() -> e);
|
||||
((ObjectNode) configMap.path("metadata"))
|
||||
.put("resourceVersion", existing.path("metadata").path("resourceVersion").asText());
|
||||
send("PUT", configMapPath(namespace, name), configMap, 200);
|
||||
@@ -199,12 +200,12 @@ public class KubernetesApiClient {
|
||||
*/
|
||||
public InputStream openPodLogStream(String namespace, String podName, String containerName) {
|
||||
ensureInitialized();
|
||||
var path = podPath(namespace, podName) + "/log?container="
|
||||
String path = podPath(namespace, podName) + "/log?container="
|
||||
+ URLEncoder.encode(containerName, StandardCharsets.UTF_8) + "&follow=true";
|
||||
try {
|
||||
var response = http.send(requestBuilder(path).GET().build(), HttpResponse.BodyHandlers.ofInputStream());
|
||||
HttpResponse<InputStream> response = http.send(requestBuilder(path).GET().build(), HttpResponse.BodyHandlers.ofInputStream());
|
||||
if (response.statusCode() != 200) {
|
||||
var body = new String(response.body().readAllBytes(), StandardCharsets.UTF_8);
|
||||
String body = new String(response.body().readAllBytes(), StandardCharsets.UTF_8);
|
||||
throw new KubernetesApiException("GET", path, response.statusCode(), body);
|
||||
}
|
||||
return response.body();
|
||||
@@ -219,14 +220,14 @@ public class KubernetesApiClient {
|
||||
private JsonNode send(String method, String path, JsonNode body, int expectedStatus) {
|
||||
ensureInitialized();
|
||||
try {
|
||||
var builder = requestBuilder(path);
|
||||
HttpRequest.Builder builder = requestBuilder(path);
|
||||
if (body != null) {
|
||||
builder.header("Content-Type", "application/json")
|
||||
.method(method, HttpRequest.BodyPublishers.ofByteArray(mapper.writeValueAsBytes(body)));
|
||||
} else {
|
||||
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
||||
}
|
||||
var response = http.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
HttpResponse<byte[]> response = http.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
if (response.statusCode() != expectedStatus) {
|
||||
throw new KubernetesApiException(method, path, response.statusCode(),
|
||||
new String(response.body(), StandardCharsets.UTF_8));
|
||||
@@ -243,7 +244,7 @@ public class KubernetesApiClient {
|
||||
private Optional<JsonNode> getOptional(String path) {
|
||||
ensureInitialized();
|
||||
try {
|
||||
var response = http.send(requestBuilder(path).GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
HttpResponse<byte[]> response = http.send(requestBuilder(path).GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
if (response.statusCode() == 404) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -261,7 +262,7 @@ public class KubernetesApiClient {
|
||||
}
|
||||
|
||||
private HttpRequest.Builder requestBuilder(String path) {
|
||||
var builder = HttpRequest.newBuilder(baseUri.resolve(path)).timeout(Duration.ofSeconds(30));
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(baseUri.resolve(path)).timeout(Duration.ofSeconds(30));
|
||||
if (tokenSupplier != null) {
|
||||
builder.header("Authorization", "Bearer " + tokenSupplier.get());
|
||||
}
|
||||
@@ -299,9 +300,9 @@ public class KubernetesApiClient {
|
||||
}
|
||||
|
||||
private void resolveInCluster() {
|
||||
var host = System.getenv("KUBERNETES_SERVICE_HOST");
|
||||
var port = System.getenv("KUBERNETES_SERVICE_PORT");
|
||||
var authority = (host != null && port != null) ? host + ":" + port : "kubernetes.default.svc";
|
||||
String host = System.getenv("KUBERNETES_SERVICE_HOST");
|
||||
String port = System.getenv("KUBERNETES_SERVICE_PORT");
|
||||
String authority = (host != null && port != null) ? host + ":" + port : "kubernetes.default.svc";
|
||||
this.baseUri = URI.create("https://" + authority);
|
||||
this.http = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
@@ -326,29 +327,29 @@ public class KubernetesApiClient {
|
||||
+ " and no kubeconfig at " + path + ". Set KUBECONFIG or place one at ~/.kube/config.");
|
||||
}
|
||||
JsonNode root;
|
||||
try (var in = Files.newInputStream(path)) {
|
||||
try (InputStream in = Files.newInputStream(path)) {
|
||||
root = new ObjectMapper(new YAMLFactory()).readTree(in);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Could not read kubeconfig at " + path + ": " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
var currentContextName = root.path("current-context").asText(null);
|
||||
String currentContextName = root.path("current-context").asText(null);
|
||||
if (currentContextName == null || currentContextName.isBlank()) {
|
||||
throw new IllegalStateException("kubeconfig at " + path + " has no current-context set");
|
||||
}
|
||||
var context = findNamed(root.path("contexts"), currentContextName, "context")
|
||||
JsonNode context = findNamed(root.path("contexts"), currentContextName, "context")
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"kubeconfig context '" + currentContextName + "' not found in " + path));
|
||||
var clusterName = context.path("cluster").asText(null);
|
||||
var cluster = findNamed(root.path("clusters"), clusterName, "cluster")
|
||||
String clusterName = context.path("cluster").asText(null);
|
||||
JsonNode cluster = findNamed(root.path("clusters"), clusterName, "cluster")
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"kubeconfig cluster '" + clusterName + "' not found in " + path));
|
||||
var userName = context.path("user").asText(null);
|
||||
var user = userName == null ? JsonNodeFactory.instance.objectNode()
|
||||
String userName = context.path("user").asText(null);
|
||||
JsonNode user = userName == null ? JsonNodeFactory.instance.objectNode()
|
||||
: findNamed(root.path("users"), userName, "user")
|
||||
.orElseGet(JsonNodeFactory.instance::objectNode);
|
||||
|
||||
var server = cluster.path("server").asText(null);
|
||||
String server = cluster.path("server").asText(null);
|
||||
if (server == null || server.isBlank()) {
|
||||
throw new IllegalStateException("kubeconfig cluster '" + clusterName + "' has no server URL in " + path);
|
||||
}
|
||||
@@ -356,23 +357,23 @@ public class KubernetesApiClient {
|
||||
|
||||
// Matches kubectl: when set, this wins over any certificate-authority (chain
|
||||
// validation is skipped either way, so a CA to validate against is moot).
|
||||
var insecureSkipTlsVerify = cluster.path("insecure-skip-tls-verify").asBoolean(false);
|
||||
boolean insecureSkipTlsVerify = cluster.path("insecure-skip-tls-verify").asBoolean(false);
|
||||
X509TrustManager trustManager;
|
||||
if (insecureSkipTlsVerify) {
|
||||
trustManager = INSECURE_TRUST_MANAGER;
|
||||
} else {
|
||||
var caBytes = pemBytes(cluster, "certificate-authority", "certificate-authority-data", path);
|
||||
byte[] caBytes = pemBytes(cluster, "certificate-authority", "certificate-authority-data", path);
|
||||
trustManager = caBytes != null ? trustManagerFromPem(caBytes) : defaultTrustManager();
|
||||
}
|
||||
|
||||
var certBytes = pemBytes(user, "client-certificate", "client-certificate-data", path);
|
||||
var keyBytes = pemBytes(user, "client-key", "client-key-data", path);
|
||||
byte[] certBytes = pemBytes(user, "client-certificate", "client-certificate-data", path);
|
||||
byte[] keyBytes = pemBytes(user, "client-key", "client-key-data", path);
|
||||
KeyManager[] keyManagers = null;
|
||||
if (certBytes != null && keyBytes != null) {
|
||||
keyManagers = keyManagersFromPem(certBytes, keyBytes);
|
||||
}
|
||||
|
||||
var token = user.path("token").asText(null);
|
||||
String token = user.path("token").asText(null);
|
||||
Supplier<String> execTokenSupplier = user.has("exec")
|
||||
? EksTokenMinter.tokenSupplierIfRecognized(user.path("exec")).orElse(null)
|
||||
: null;
|
||||
@@ -389,14 +390,14 @@ public class KubernetesApiClient {
|
||||
+ "' has no supported credential (token or client-certificate/client-key) in " + path);
|
||||
}
|
||||
|
||||
var httpBuilder = HttpClient.newBuilder()
|
||||
HttpClient.Builder httpBuilder = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.sslContext(sslContext(trustManager, keyManagers));
|
||||
if (insecureSkipTlsVerify) {
|
||||
// The trust manager above already skips chain validation; this additionally
|
||||
// skips hostname verification, matching kubectl's --insecure-skip-tls-verify
|
||||
// (otherwise a kind/minikube server cert with no matching SAN still fails).
|
||||
var sslParameters = new SSLParameters();
|
||||
SSLParameters sslParameters = new SSLParameters();
|
||||
sslParameters.setEndpointIdentificationAlgorithm("");
|
||||
httpBuilder.sslParameters(sslParameters);
|
||||
}
|
||||
@@ -406,9 +407,9 @@ public class KubernetesApiClient {
|
||||
}
|
||||
|
||||
private static Path kubeconfigPath() {
|
||||
var envValue = System.getenv("KUBECONFIG");
|
||||
String envValue = System.getenv("KUBECONFIG");
|
||||
if (envValue != null && !envValue.isBlank()) {
|
||||
var separator = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win") ? ";" : ":";
|
||||
String separator = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win") ? ";" : ":";
|
||||
return Path.of(envValue.split(Pattern.quote(separator))[0]);
|
||||
}
|
||||
return Path.of(System.getProperty("user.home"), ".kube", "config");
|
||||
@@ -418,7 +419,7 @@ public class KubernetesApiClient {
|
||||
if (name == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
for (var entry : array) {
|
||||
for (JsonNode entry : array) {
|
||||
if (name.equals(entry.path("name").asText(null))) {
|
||||
return Optional.of(entry.path(childKey));
|
||||
}
|
||||
@@ -428,15 +429,15 @@ public class KubernetesApiClient {
|
||||
|
||||
/** Reads a `<field>` (a path, resolved relative to the kubeconfig) or `<field>-data` (base64) entry. */
|
||||
private static byte[] pemBytes(JsonNode node, String fileField, String dataField, Path kubeconfigPath) {
|
||||
var data = node.path(dataField).asText(null);
|
||||
String data = node.path(dataField).asText(null);
|
||||
if (data != null && !data.isBlank()) {
|
||||
return Base64.getDecoder().decode(data);
|
||||
}
|
||||
var file = node.path(fileField).asText(null);
|
||||
String file = node.path(fileField).asText(null);
|
||||
if (file == null || file.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
var resolved = Path.of(file).isAbsolute() ? Path.of(file) : kubeconfigPath.getParent().resolve(file);
|
||||
Path resolved = Path.of(file).isAbsolute() ? Path.of(file) : kubeconfigPath.getParent().resolve(file);
|
||||
try {
|
||||
return Files.readAllBytes(resolved);
|
||||
} catch (IOException e) {
|
||||
@@ -456,14 +457,14 @@ public class KubernetesApiClient {
|
||||
|
||||
private static X509TrustManager trustManagerFromPem(byte[] pem) {
|
||||
try {
|
||||
var certs = CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(pem));
|
||||
var keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
Collection<? extends Certificate> certs = CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(pem));
|
||||
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
keyStore.load(null, null);
|
||||
var i = 0;
|
||||
for (var cert : certs) {
|
||||
int i = 0;
|
||||
for (Certificate cert : certs) {
|
||||
keyStore.setCertificateEntry("ca" + (i++), cert);
|
||||
}
|
||||
var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
trustManagerFactory.init(keyStore);
|
||||
return firstX509(trustManagerFactory.getTrustManagers(),
|
||||
"No X509TrustManager produced from the supplied CA certificate(s)");
|
||||
@@ -475,7 +476,7 @@ public class KubernetesApiClient {
|
||||
|
||||
private static X509TrustManager defaultTrustManager() {
|
||||
try {
|
||||
var trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
trustManagerFactory.init((KeyStore) null);
|
||||
return firstX509(trustManagerFactory.getTrustManagers(), "No default X509TrustManager available");
|
||||
} catch (GeneralSecurityException e) {
|
||||
@@ -484,7 +485,7 @@ public class KubernetesApiClient {
|
||||
}
|
||||
|
||||
private static X509TrustManager firstX509(TrustManager[] managers, String errorIfNone) {
|
||||
for (var manager : managers) {
|
||||
for (TrustManager manager : managers) {
|
||||
if (manager instanceof X509TrustManager x509) {
|
||||
return x509;
|
||||
}
|
||||
@@ -494,12 +495,12 @@ public class KubernetesApiClient {
|
||||
|
||||
private static KeyManager[] keyManagersFromPem(byte[] certPem, byte[] keyPem) {
|
||||
try {
|
||||
var cert = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certPem));
|
||||
var privateKey = privateKeyFromPem(keyPem);
|
||||
var keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
Certificate cert = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certPem));
|
||||
PrivateKey privateKey = privateKeyFromPem(keyPem);
|
||||
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
keyStore.load(null, null);
|
||||
keyStore.setKeyEntry("client", privateKey, new char[0], new Certificate[]{cert});
|
||||
var keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
|
||||
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
|
||||
keyManagerFactory.init(keyStore, new char[0]);
|
||||
return keyManagerFactory.getKeyManagers();
|
||||
} catch (GeneralSecurityException | IOException e) {
|
||||
@@ -509,19 +510,19 @@ public class KubernetesApiClient {
|
||||
}
|
||||
|
||||
private static PrivateKey privateKeyFromPem(byte[] pem) {
|
||||
var text = new String(pem, StandardCharsets.US_ASCII);
|
||||
String text = new String(pem, StandardCharsets.US_ASCII);
|
||||
if (text.contains("BEGIN RSA PRIVATE KEY") || text.contains("BEGIN EC PRIVATE KEY")) {
|
||||
throw new IllegalStateException(
|
||||
"kubeconfig client-key is in PKCS#1 format (BEGIN RSA/EC PRIVATE KEY); only PKCS#8 "
|
||||
+ "(BEGIN PRIVATE KEY) is supported. Convert it with: openssl pkcs8 -topk8 "
|
||||
+ "-nocrypt -in key.pem -out key-pkcs8.pem");
|
||||
}
|
||||
var base64 = text.replaceAll("-----BEGIN [^-]+-----", "")
|
||||
String base64 = text.replaceAll("-----BEGIN [^-]+-----", "")
|
||||
.replaceAll("-----END [^-]+-----", "")
|
||||
.replaceAll("\\s", "");
|
||||
var keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64));
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64));
|
||||
GeneralSecurityException last = null;
|
||||
for (var algorithm : new String[]{"RSA", "EC"}) {
|
||||
for (String algorithm : new String[]{"RSA", "EC"}) {
|
||||
try {
|
||||
return KeyFactory.getInstance(algorithm).generatePrivate(keySpec);
|
||||
} catch (GeneralSecurityException e) {
|
||||
@@ -534,7 +535,7 @@ public class KubernetesApiClient {
|
||||
|
||||
private static SSLContext sslContext(X509TrustManager trustManager, KeyManager[] keyManagers) {
|
||||
try {
|
||||
var context = SSLContext.getInstance("TLS");
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(keyManagers, new TrustManager[]{trustManager}, null);
|
||||
return context;
|
||||
} catch (GeneralSecurityException e) {
|
||||
|
||||
+10
-8
@@ -10,6 +10,8 @@ import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Resolves the address Lambda pods use to reach the Floci process: the Runtime API
|
||||
@@ -53,7 +55,7 @@ public class KubernetesFlociAddressResolver {
|
||||
* Docker/embedded-DNS specific.
|
||||
*/
|
||||
public String flociBaseUrl() {
|
||||
var scheme = config.tls().enabled() ? "https" : "http";
|
||||
String scheme = config.tls().enabled() ? "https" : "http";
|
||||
return scheme + "://" + resolve() + ":" + mainPort();
|
||||
}
|
||||
|
||||
@@ -75,10 +77,10 @@ public class KubernetesFlociAddressResolver {
|
||||
}
|
||||
|
||||
private String doResolve() {
|
||||
var override = config.services().lambda().kubernetes().flociAddress()
|
||||
Optional<String> override = config.services().lambda().kubernetes().flociAddress()
|
||||
.filter(s -> !s.isBlank());
|
||||
if (override.isPresent()) {
|
||||
var address = override.get().trim();
|
||||
String address = override.get().trim();
|
||||
// Reachability can only be judged from the pods' network, not from here,
|
||||
// but anything beyond hostname/IP characters is always a mistake worth
|
||||
// failing on: the value is embedded in URLs and in single-quoted
|
||||
@@ -115,7 +117,7 @@ public class KubernetesFlociAddressResolver {
|
||||
// IPv4 only: an IPv6 literal would need bracketing in every URL this address
|
||||
// feeds, and busybox wget cannot fetch from unbracketed IPv6 hosts.
|
||||
try {
|
||||
var local = InetAddress.getLocalHost();
|
||||
InetAddress local = InetAddress.getLocalHost();
|
||||
if (local instanceof Inet4Address && !local.isLoopbackAddress()) {
|
||||
return local.getHostAddress();
|
||||
}
|
||||
@@ -123,15 +125,15 @@ public class KubernetesFlociAddressResolver {
|
||||
LOG.debugv("getLocalHost failed, scanning interfaces: {0}", e.getMessage());
|
||||
}
|
||||
try {
|
||||
var interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (interfaces.hasMoreElements()) {
|
||||
var nic = interfaces.nextElement();
|
||||
NetworkInterface nic = interfaces.nextElement();
|
||||
if (!nic.isUp() || nic.isLoopback()) {
|
||||
continue;
|
||||
}
|
||||
var addresses = nic.getInetAddresses();
|
||||
Enumeration<InetAddress> addresses = nic.getInetAddresses();
|
||||
while (addresses.hasMoreElements()) {
|
||||
var address = addresses.nextElement();
|
||||
InetAddress address = addresses.nextElement();
|
||||
if (address instanceof Inet4Address && !address.isLoopbackAddress()) {
|
||||
return address.getHostAddress();
|
||||
}
|
||||
|
||||
+49
-45
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.ContainerCaBundle;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
@@ -15,6 +16,8 @@ import io.github.hectorvent.floci.services.lambda.launcher.ImageResolver;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.LambdaRuntimeLauncher;
|
||||
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
|
||||
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
|
||||
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -22,6 +25,7 @@ import jakarta.enterprise.inject.Typed;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
@@ -145,35 +149,35 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
+ "kubernetes executor; pods receive placeholder credentials instead");
|
||||
}
|
||||
|
||||
var namespace = namespace();
|
||||
String namespace = namespace();
|
||||
sweepOrphansOnce(namespace);
|
||||
LOG.infov("Launching pod for function: {0}", fn.getFunctionName());
|
||||
|
||||
var runtimeApiServer = runtimeApiServerFactory.create();
|
||||
RuntimeApiServer runtimeApiServer = runtimeApiServerFactory.create();
|
||||
|
||||
// Mirrors ContainerLauncher: any failure after the runtime-api server is allocated
|
||||
// must release its port and delete a half-created pod, or cold-start bursts leak
|
||||
// ports until the pool is exhausted.
|
||||
String podName = null;
|
||||
try {
|
||||
var imagePackage = "Image".equals(fn.getPackageType()) && fn.getImageUri() != null;
|
||||
boolean imagePackage = "Image".equals(fn.getPackageType()) && fn.getImageUri() != null;
|
||||
// No emulated-ECR rewrite here: the kubelet pulls images, and Floci's loopback
|
||||
// registry is not reachable from cluster nodes. URIs pass through unchanged.
|
||||
var image = imagePackage ? fn.getImageUri() : imageResolver.resolve(fn.getRuntime());
|
||||
String image = imagePackage ? fn.getImageUri() : imageResolver.resolve(fn.getRuntime());
|
||||
|
||||
var shortId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
String shortId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
podName = LambdaPodSpecFactory.podName(fn.getFunctionName(), shortId);
|
||||
var region = AwsArnUtils.regionOrDefault(fn.getFunctionArn(), config.defaultRegion());
|
||||
String region = AwsArnUtils.regionOrDefault(fn.getFunctionArn(), config.defaultRegion());
|
||||
String accountId = AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId());
|
||||
var cwLogGroup = "/aws/lambda/" + fn.getFunctionName();
|
||||
var cwLogStream = logStreamer.logStreamName(shortId);
|
||||
String cwLogGroup = "/aws/lambda/" + fn.getFunctionName();
|
||||
String cwLogStream = logStreamer.logStreamName(shortId);
|
||||
|
||||
var codeDownloadUrl = imagePackage ? null : codeDownloadUrl(fn, region);
|
||||
var layerUrls = imagePackage ? List.<String>of() : layerDownloadUrls(fn, region);
|
||||
String codeDownloadUrl = imagePackage ? null : codeDownloadUrl(fn, region);
|
||||
List<String> layerUrls = imagePackage ? List.of() : layerDownloadUrls(fn, region);
|
||||
|
||||
var caConfigMap = ContainerCaBundle.hostPath(config).map(bundle -> ensureCaConfigMap(namespace, bundle));
|
||||
Optional<String> caConfigMap = ContainerCaBundle.hostPath(config).map(bundle -> ensureCaConfigMap(namespace, bundle));
|
||||
|
||||
var env = new ArrayList<String>();
|
||||
ArrayList<String> env = new ArrayList<>();
|
||||
env.add("AWS_LAMBDA_RUNTIME_API=" + addressResolver.resolve() + ":" + runtimeApiServer.getPort());
|
||||
env.add("AWS_LAMBDA_FUNCTION_NAME=" + fn.getFunctionName());
|
||||
env.add("AWS_LAMBDA_FUNCTION_MEMORY_SIZE=" + fn.getMemorySize());
|
||||
@@ -200,14 +204,14 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
});
|
||||
}
|
||||
|
||||
var imageConfig = imagePackage
|
||||
LambdaPodSpecFactory.ImageConfig imageConfig = imagePackage
|
||||
? new LambdaPodSpecFactory.ImageConfig(fn.getImageConfigEntryPoint(),
|
||||
fn.getImageConfigCommand(), fn.getImageConfigWorkingDirectory())
|
||||
: null;
|
||||
|
||||
// After the function's own variables, so a value it sets wins, as in the docker launcher.
|
||||
var podEnv = caConfigMap.isPresent() ? ContainerCaBundle.appendEnv(env) : env;
|
||||
var pod = podSpecFactory.buildPod(podName, fn.getFunctionName(), image, podEnv,
|
||||
List<String> podEnv = caConfigMap.isPresent() ? ContainerCaBundle.appendEnv(env) : env;
|
||||
ObjectNode pod = podSpecFactory.buildPod(podName, fn.getFunctionName(), image, podEnv,
|
||||
codeDownloadUrl, layerUrls, isProvidedRuntime(fn.getRuntime()),
|
||||
imagePackage ? null : fn.getHandler(), imageConfig, fn.getMemorySize(), caConfigMap);
|
||||
|
||||
@@ -217,13 +221,13 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
|
||||
awaitRunning(namespace, podName, fn.getFunctionName());
|
||||
|
||||
var handle = new ContainerHandle(podName, fn.getFunctionName(),
|
||||
ContainerHandle handle = new ContainerHandle(podName, fn.getFunctionName(),
|
||||
runtimeApiServer, ContainerState.WARM, false);
|
||||
// Log streaming is non-essential and runs after the pod is already Running,
|
||||
// so a failure here (e.g. a missing pods/log RBAC verb) must not tear down a
|
||||
// healthy execution environment.
|
||||
try {
|
||||
var logHandle = logStreamer.attachForAccount(accountId, namespace, podName,
|
||||
Closeable logHandle = logStreamer.attachForAccount(accountId, namespace, podName,
|
||||
cwLogGroup, cwLogStream, region, "lambda:" + fn.getFunctionName());
|
||||
handle.setLogStream(logHandle);
|
||||
} catch (Exception logFailure) {
|
||||
@@ -304,7 +308,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
@Override
|
||||
public boolean isAlive(ContainerHandle handle) {
|
||||
try {
|
||||
var pod = client.getPod(namespace(), handle.getContainerId()).orElse(null);
|
||||
JsonNode pod = client.getPod(namespace(), handle.getContainerId()).orElse(null);
|
||||
return pod != null
|
||||
&& "Running".equals(pod.path("status").path("phase").asText(null))
|
||||
&& isAbsent(pod.path("metadata").path("deletionTimestamp"));
|
||||
@@ -343,13 +347,13 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
var orphans = client.listPods(namespace, LambdaPodSpecFactory.managedPodSelector()).stream()
|
||||
List<JsonNode> orphans = client.listPods(namespace, LambdaPodSpecFactory.managedPodSelector()).stream()
|
||||
.filter(pod -> !ownPodNames.contains(pod.path("metadata").path("name").asText()))
|
||||
.toList();
|
||||
if (!orphans.isEmpty()) {
|
||||
LOG.infov("Deleting {0} orphaned Lambda pod(s) from a previous run in namespace {1}",
|
||||
orphans.size(), namespace);
|
||||
for (var orphan : orphans) {
|
||||
for (JsonNode orphan : orphans) {
|
||||
client.deletePod(namespace, orphan.path("metadata").path("name").asText());
|
||||
}
|
||||
}
|
||||
@@ -374,8 +378,8 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
private String codeDownloadUrl(LambdaFunction fn, String region) {
|
||||
var bucket = LambdaService.tasksBucketName(region);
|
||||
var key = LambdaService.codeObjectKey(fn);
|
||||
String bucket = LambdaService.tasksBucketName(region);
|
||||
String key = LambdaService.codeObjectKey(fn);
|
||||
try {
|
||||
s3Service.headObject(bucket, key);
|
||||
} catch (AwsException e) {
|
||||
@@ -384,7 +388,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
+ " — the kubernetes executor downloads code from Floci's S3, and the copy "
|
||||
+ "stored at deploy time is missing. Re-deploy the function code.", e);
|
||||
}
|
||||
var account = fn.getAccountId() != null ? fn.getAccountId() : config.defaultAccountId();
|
||||
String account = fn.getAccountId() != null ? fn.getAccountId() : config.defaultAccountId();
|
||||
return downloadUrl(bucket, key, account, region);
|
||||
}
|
||||
|
||||
@@ -392,20 +396,20 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
if (fn.getLayers() == null || fn.getLayers().isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
var urls = new ArrayList<String>();
|
||||
for (var layerArn : fn.getLayers()) {
|
||||
var layer = layerService.resolveLayerByArn(layerArn);
|
||||
ArrayList<String> urls = new ArrayList<>();
|
||||
for (String layerArn : fn.getLayers()) {
|
||||
LambdaLayerVersion layer = layerService.resolveLayerByArn(layerArn);
|
||||
if (layer == null) {
|
||||
LOG.warnv("Could not resolve layer ARN {0} for function {1}", layerArn, fn.getFunctionName());
|
||||
continue;
|
||||
}
|
||||
// The archive lives under the layer's own region and account (the canonical
|
||||
// ARN assigned at publish), which may differ from the function's.
|
||||
var arn = layer.getLayerVersionArn();
|
||||
var layerRegion = AwsArnUtils.regionOrDefault(arn, functionRegion);
|
||||
var account = AwsArnUtils.accountOrDefault(arn, config.defaultAccountId());
|
||||
var bucket = LambdaService.tasksBucketName(layerRegion);
|
||||
var key = LambdaService.layerObjectKey(account, layer.getLayerName(), layer.getVersion());
|
||||
String arn = layer.getLayerVersionArn();
|
||||
String layerRegion = AwsArnUtils.regionOrDefault(arn, functionRegion);
|
||||
String account = AwsArnUtils.accountOrDefault(arn, config.defaultAccountId());
|
||||
String bucket = LambdaService.tasksBucketName(layerRegion);
|
||||
String key = LambdaService.layerObjectKey(account, layer.getLayerName(), layer.getVersion());
|
||||
try {
|
||||
s3Service.headObject(bucket, key);
|
||||
} catch (AwsException e) {
|
||||
@@ -432,7 +436,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
private void awaitRunning(String namespace, String podName, String functionName) {
|
||||
var timeoutSeconds = POD_STARTUP_TIMEOUT_SECONDS;
|
||||
int timeoutSeconds = POD_STARTUP_TIMEOUT_SECONDS;
|
||||
JsonNode pod;
|
||||
try {
|
||||
// A missing pod (deleted out-of-band) is terminal too, otherwise the wait
|
||||
@@ -454,7 +458,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
private static boolean hasTerminalFailure(JsonNode pod) {
|
||||
var phase = pod.path("status").path("phase").asText(null);
|
||||
String phase = pod.path("status").path("phase").asText(null);
|
||||
// Succeeded means the runtime exited before serving — terminal for a server pod.
|
||||
if ("Failed".equals(phase) || "Succeeded".equals(phase)) {
|
||||
return true;
|
||||
@@ -463,7 +467,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
private static String unschedulableReason(JsonNode pod) {
|
||||
for (var condition : pod.path("status").path("conditions")) {
|
||||
for (JsonNode condition : pod.path("status").path("conditions")) {
|
||||
// A pod the scheduler cannot place — e.g. a memory request above every node's
|
||||
// capacity — stays Pending with no container statuses; fail the cold start
|
||||
// instead of blocking the invoker for the full startup timeout.
|
||||
@@ -477,18 +481,18 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
private static String describeTerminalReason(JsonNode pod) {
|
||||
for (var statuses : List.of(pod.path("status").path("initContainerStatuses"),
|
||||
for (JsonNode statuses : List.of(pod.path("status").path("initContainerStatuses"),
|
||||
pod.path("status").path("containerStatuses"))) {
|
||||
for (var status : statuses) {
|
||||
var waiting = status.path("state").path("waiting");
|
||||
var waitingReason = waiting.path("reason").asText(null);
|
||||
for (JsonNode status : statuses) {
|
||||
JsonNode waiting = status.path("state").path("waiting");
|
||||
String waitingReason = waiting.path("reason").asText(null);
|
||||
// A missing reason must never match; Set.of(...).contains(null) throws,
|
||||
// which would abort an otherwise healthy cold start.
|
||||
if (waitingReason != null && TERMINAL_WAITING_REASONS.contains(waitingReason)) {
|
||||
return status.path("name").asText() + ": " + waitingReason
|
||||
+ " (" + waiting.path("message").asText("") + ")";
|
||||
}
|
||||
var exitCode = status.path("state").path("terminated").path("exitCode");
|
||||
JsonNode exitCode = status.path("state").path("terminated").path("exitCode");
|
||||
if (!exitCode.isMissingNode() && exitCode.asInt() != 0) {
|
||||
return status.path("name").asText() + ": exited with code " + exitCode.asInt();
|
||||
}
|
||||
@@ -501,7 +505,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
if (pod == null || pod.path("status").isMissingNode()) {
|
||||
return "pod no longer exists";
|
||||
}
|
||||
var reason = describeTerminalReason(pod);
|
||||
String reason = describeTerminalReason(pod);
|
||||
if (reason == null) {
|
||||
reason = unschedulableReason(pod);
|
||||
}
|
||||
@@ -522,13 +526,13 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
return CA_CONFIG_MAP_NAME;
|
||||
}
|
||||
try {
|
||||
var pem = Files.readString(bundle);
|
||||
var nodes = JsonNodeFactory.instance;
|
||||
var labels = nodes.objectNode();
|
||||
String pem = Files.readString(bundle);
|
||||
JsonNodeFactory nodes = JsonNodeFactory.instance;
|
||||
ObjectNode labels = nodes.objectNode();
|
||||
LambdaPodSpecFactory.managedPodSelector().forEach(labels::put);
|
||||
var metadata = nodes.objectNode().put("name", CA_CONFIG_MAP_NAME);
|
||||
ObjectNode metadata = nodes.objectNode().put("name", CA_CONFIG_MAP_NAME);
|
||||
metadata.set("labels", labels);
|
||||
var configMap = nodes.objectNode().put("apiVersion", "v1").put("kind", "ConfigMap");
|
||||
ObjectNode configMap = nodes.objectNode().put("apiVersion", "v1").put("kind", "ConfigMap");
|
||||
configMap.set("metadata", metadata);
|
||||
configMap.set("data", nodes.objectNode().put(CA_CONFIG_MAP_KEY, pem));
|
||||
client.createOrUpdateConfigMap(namespace, configMap);
|
||||
|
||||
+3
-3
@@ -49,13 +49,13 @@ public class KubernetesPodLogStreamer {
|
||||
InputStream logStreamBody = client.openPodLogStream(namespace, podName, "runtime");
|
||||
|
||||
// Virtual thread: one blocking reader per warm pod is near-free this way.
|
||||
var reader = Thread.ofVirtual().name("lambda-pod-logs-" + podName).start(() -> {
|
||||
try (var lines = new BufferedReader(new InputStreamReader(logStreamBody, StandardCharsets.UTF_8))) {
|
||||
Thread reader = Thread.ofVirtual().name("lambda-pod-logs-" + podName).start(() -> {
|
||||
try (BufferedReader lines = new BufferedReader(new InputStreamReader(logStreamBody, StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = lines.readLine()) != null) {
|
||||
// Match the docker log path: trim trailing whitespace and drop blank
|
||||
// lines so both executors write identical CloudWatch events.
|
||||
var trimmed = line.stripTrailing();
|
||||
String trimmed = line.stripTrailing();
|
||||
if (trimmed.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
+33
-33
@@ -73,12 +73,12 @@ public class LambdaPodSpecFactory {
|
||||
ImageConfig imageConfig,
|
||||
int memoryMb,
|
||||
Optional<String> caConfigMapName) {
|
||||
var hasCode = codeDownloadUrl != null;
|
||||
var hasLayers = !layerDownloadUrls.isEmpty();
|
||||
var nodes = JsonNodeFactory.instance;
|
||||
boolean hasCode = codeDownloadUrl != null;
|
||||
boolean hasLayers = !layerDownloadUrls.isEmpty();
|
||||
JsonNodeFactory nodes = JsonNodeFactory.instance;
|
||||
|
||||
var volumes = nodes.arrayNode();
|
||||
var runtimeMounts = nodes.arrayNode();
|
||||
ArrayNode volumes = nodes.arrayNode();
|
||||
ArrayNode runtimeMounts = nodes.arrayNode();
|
||||
if (hasCode) {
|
||||
volumes.add(emptyDirVolume(nodes, "task"));
|
||||
runtimeMounts.add(mount(nodes, "task", TASK_DIR));
|
||||
@@ -90,7 +90,7 @@ public class LambdaPodSpecFactory {
|
||||
// The provided.* base images exec /var/runtime/bootstrap with no /var/task
|
||||
// fallback, and their /var/runtime ships empty, so masking it with an emptyDir
|
||||
// that the init container copies bootstrap into is safe and required.
|
||||
var needsRuntimeDir = providedRuntime && hasCode;
|
||||
boolean needsRuntimeDir = providedRuntime && hasCode;
|
||||
if (needsRuntimeDir) {
|
||||
volumes.add(emptyDirVolume(nodes, "runtime"));
|
||||
runtimeMounts.add(mount(nodes, "runtime", RUNTIME_DIR));
|
||||
@@ -105,12 +105,12 @@ public class LambdaPodSpecFactory {
|
||||
.put("readOnly", true));
|
||||
});
|
||||
|
||||
var resources = nodes.objectNode();
|
||||
var memory = memoryMb + "Mi";
|
||||
ObjectNode resources = nodes.objectNode();
|
||||
String memory = memoryMb + "Mi";
|
||||
resources.set("requests", nodes.objectNode().put("memory", memory));
|
||||
resources.set("limits", nodes.objectNode().put("memory", memory));
|
||||
|
||||
var runtime = nodes.objectNode()
|
||||
ObjectNode runtime = nodes.objectNode()
|
||||
.put("name", "runtime")
|
||||
.put("image", image)
|
||||
// Explicit IfNotPresent: the default for :latest/untagged is Always,
|
||||
@@ -133,9 +133,9 @@ public class LambdaPodSpecFactory {
|
||||
runtime.put("workingDir", imageConfig.workingDirectory());
|
||||
}
|
||||
|
||||
var initContainers = nodes.arrayNode();
|
||||
ArrayNode initContainers = nodes.arrayNode();
|
||||
if (hasCode) {
|
||||
var initMounts = nodes.arrayNode();
|
||||
ArrayNode initMounts = nodes.arrayNode();
|
||||
initMounts.add(mount(nodes, "task", TASK_DIR));
|
||||
if (hasLayers) {
|
||||
initMounts.add(mount(nodes, "opt", OPT_DIR));
|
||||
@@ -143,7 +143,7 @@ public class LambdaPodSpecFactory {
|
||||
if (needsRuntimeDir) {
|
||||
initMounts.add(mount(nodes, "runtime", RUNTIME_DIR));
|
||||
}
|
||||
var init = nodes.objectNode()
|
||||
ObjectNode init = nodes.objectNode()
|
||||
.put("name", "code-download")
|
||||
.put("image", config.services().lambda().kubernetes().initImage())
|
||||
.put("imagePullPolicy", "IfNotPresent");
|
||||
@@ -153,19 +153,19 @@ public class LambdaPodSpecFactory {
|
||||
initContainers.add(init);
|
||||
}
|
||||
|
||||
var metadata = nodes.objectNode().put("name", podName);
|
||||
var labels = nodes.objectNode();
|
||||
ObjectNode metadata = nodes.objectNode().put("name", podName);
|
||||
ObjectNode labels = nodes.objectNode();
|
||||
podLabels(functionName).forEach(labels::put);
|
||||
metadata.set("labels", labels);
|
||||
|
||||
var spec = nodes.objectNode()
|
||||
ObjectNode spec = nodes.objectNode()
|
||||
.put("restartPolicy", "Never")
|
||||
.put("terminationGracePeriodSeconds", 5);
|
||||
spec.set("initContainers", initContainers);
|
||||
spec.set("containers", nodes.arrayNode().add(runtime));
|
||||
spec.set("volumes", volumes);
|
||||
|
||||
var pod = nodes.objectNode()
|
||||
ObjectNode pod = nodes.objectNode()
|
||||
.put("apiVersion", "v1")
|
||||
.put("kind", "Pod");
|
||||
pod.set("metadata", metadata);
|
||||
@@ -184,11 +184,11 @@ public class LambdaPodSpecFactory {
|
||||
String initScript(String codeDownloadUrl, List<String> layerDownloadUrls, boolean providedRuntime) {
|
||||
// Download URLs are always plain HTTP (see KubernetesFlociAddressResolver
|
||||
// .downloadBaseUrl): busybox wget's built-in TLS cannot handshake with Floci.
|
||||
var wget = "wget -q";
|
||||
var script = new StringBuilder("set -e\n");
|
||||
String wget = "wget -q";
|
||||
StringBuilder script = new StringBuilder("set -e\n");
|
||||
script.append(wget).append(" -O /tmp/code.zip '").append(codeDownloadUrl).append("'\n");
|
||||
script.append("unzip -oq /tmp/code.zip -d ").append(TASK_DIR).append("\n");
|
||||
for (var i = 0; i < layerDownloadUrls.size(); i++) {
|
||||
for (int i = 0; i < layerDownloadUrls.size(); i++) {
|
||||
script.append(wget).append(" -O /tmp/layer").append(i).append(".zip '")
|
||||
.append(layerDownloadUrls.get(i)).append("'\n");
|
||||
script.append("unzip -oq /tmp/layer").append(i).append(".zip -d ").append(OPT_DIR).append("\n");
|
||||
@@ -206,11 +206,11 @@ public class LambdaPodSpecFactory {
|
||||
}
|
||||
|
||||
Map<String, String> podLabels(String functionName) {
|
||||
var labels = new LinkedHashMap<String, String>();
|
||||
LinkedHashMap<String, String> labels = new LinkedHashMap<>();
|
||||
config.services().lambda().kubernetes().labels().orElse(List.of()).forEach(entry -> {
|
||||
var eq = entry.indexOf('=');
|
||||
var key = eq > 0 ? entry.substring(0, eq).trim() : "";
|
||||
var value = eq > 0 ? entry.substring(eq + 1).trim() : "";
|
||||
int eq = entry.indexOf('=');
|
||||
String key = eq > 0 ? entry.substring(0, eq).trim() : "";
|
||||
String value = eq > 0 ? entry.substring(eq + 1).trim() : "";
|
||||
// Invalid entries are dropped, not sanitized: a silently rewritten label
|
||||
// would no longer match the NetworkPolicy/selector the user wrote it for,
|
||||
// and the API server would reject the pod at cold start otherwise.
|
||||
@@ -239,9 +239,9 @@ public class LambdaPodSpecFactory {
|
||||
* suffix stays intact; the function name is truncated to fit.
|
||||
*/
|
||||
static String podName(String functionName, String shortId) {
|
||||
var prefix = "floci-lambda-";
|
||||
var sanitized = functionName.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9-]", "-");
|
||||
var budget = MAX_NAME_LENGTH - prefix.length() - shortId.length() - 1;
|
||||
String prefix = "floci-lambda-";
|
||||
String sanitized = functionName.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9-]", "-");
|
||||
int budget = MAX_NAME_LENGTH - prefix.length() - shortId.length() - 1;
|
||||
if (sanitized.length() > budget) {
|
||||
sanitized = sanitized.substring(0, budget);
|
||||
}
|
||||
@@ -254,7 +254,7 @@ public class LambdaPodSpecFactory {
|
||||
|
||||
/** Label values allow [a-zA-Z0-9-_.], max 63 chars, alphanumeric at both ends. */
|
||||
static String sanitizeLabelValue(String value) {
|
||||
var sanitized = value.replaceAll("[^a-zA-Z0-9-_.]", "-");
|
||||
String sanitized = value.replaceAll("[^a-zA-Z0-9-_.]", "-");
|
||||
if (sanitized.length() > MAX_NAME_LENGTH) {
|
||||
sanitized = sanitized.substring(0, MAX_NAME_LENGTH);
|
||||
}
|
||||
@@ -271,7 +271,7 @@ public class LambdaPodSpecFactory {
|
||||
}
|
||||
|
||||
private static ArrayNode stringArray(JsonNodeFactory nodes, List<String> values) {
|
||||
var array = nodes.arrayNode();
|
||||
ArrayNode array = nodes.arrayNode();
|
||||
values.forEach(array::add);
|
||||
return array;
|
||||
}
|
||||
@@ -287,11 +287,11 @@ public class LambdaPodSpecFactory {
|
||||
}
|
||||
|
||||
private static ArrayNode toEnvVars(JsonNodeFactory nodes, List<String> env) {
|
||||
var vars = nodes.arrayNode();
|
||||
for (var entry : env) {
|
||||
var eq = entry.indexOf('=');
|
||||
var key = eq >= 0 ? entry.substring(0, eq) : entry;
|
||||
var value = eq >= 0 ? entry.substring(eq + 1) : "";
|
||||
ArrayNode vars = nodes.arrayNode();
|
||||
for (String entry : env) {
|
||||
int eq = entry.indexOf('=');
|
||||
String key = eq >= 0 ? entry.substring(0, eq) : entry;
|
||||
String value = eq >= 0 ? entry.substring(eq + 1) : "";
|
||||
// The API server rejects a pod whose env var has an empty name.
|
||||
if (key.isEmpty()) {
|
||||
LOG.warnv("Skipping env entry with an empty name in the pod spec: ''{0}''", entry);
|
||||
|
||||
+1
-1
@@ -420,7 +420,7 @@ public class RuntimeApiServer {
|
||||
return;
|
||||
}
|
||||
List<String> events = List.of("INVOKE", "SHUTDOWN");
|
||||
var body = ctx.body().asJsonObject();
|
||||
JsonObject body = ctx.body().asJsonObject();
|
||||
if (body != null && body.getJsonArray("events") != null) {
|
||||
events = body.getJsonArray("events").stream().map(String::valueOf).toList();
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Manages on-disk locations of extracted Lambda function code.
|
||||
@@ -101,7 +102,7 @@ public class CodeStore {
|
||||
}
|
||||
Path target = getVersionCodePath(accountId, region, functionName, version);
|
||||
deleteDirectory(target, functionName);
|
||||
try (var walk = Files.walk(source)) {
|
||||
try (Stream<Path> walk = Files.walk(source)) {
|
||||
for (Path from : walk.toList()) {
|
||||
Path to = target.resolve(source.relativize(from).toString());
|
||||
if (Files.isDirectory(from)) {
|
||||
@@ -148,7 +149,7 @@ public class CodeStore {
|
||||
if (!Files.exists(path)) {
|
||||
return;
|
||||
}
|
||||
try (var walk = Files.walk(path)) {
|
||||
try (Stream<Path> walk = Files.walk(path)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(p -> {
|
||||
try {
|
||||
@@ -168,7 +169,7 @@ public class CodeStore {
|
||||
if (!Files.exists(codePath)) {
|
||||
return false;
|
||||
}
|
||||
try (var listing = Files.list(codePath)) {
|
||||
try (Stream<Path> listing = Files.list(codePath)) {
|
||||
return listing.findAny().isPresent();
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
|
||||
@@ -11,7 +11,9 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Comparator;
|
||||
import java.util.Enumeration;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipException;
|
||||
@@ -81,7 +83,7 @@ public class ZipExtractor {
|
||||
try {
|
||||
Files.write(staged, zipBytes);
|
||||
try (ZipFile zip = new ZipFile(staged.toFile())) {
|
||||
var entries = zip.entries();
|
||||
Enumeration<? extends ZipEntry> entries = zip.entries();
|
||||
int entryCount = 0;
|
||||
long expandedBytes = 0;
|
||||
while (entries.hasMoreElements()) {
|
||||
@@ -224,7 +226,7 @@ public class ZipExtractor {
|
||||
if (!Files.exists(root)) {
|
||||
return;
|
||||
}
|
||||
try (var paths = Files.walk(root)) {
|
||||
try (Stream<Path> paths = Files.walk(root)) {
|
||||
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
Files.deleteIfExists(p);
|
||||
}
|
||||
|
||||
+3
-2
@@ -15,6 +15,7 @@ import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -109,9 +110,9 @@ public class MarketplaceEntitlementService implements Resettable {
|
||||
if (filter == null || filter.isNull()) {
|
||||
return true;
|
||||
}
|
||||
var fields = filter.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = filter.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
String actual = switch (entry.getKey()) {
|
||||
case "CUSTOMER_IDENTIFIER" -> entitlement.customerIdentifier();
|
||||
case "CUSTOMER_AWS_ACCOUNT_ID" -> entitlement.customerAwsAccountId();
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.memorydb;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
@@ -26,6 +27,7 @@ import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@@ -526,7 +528,7 @@ public class MemoryDbService {
|
||||
throw new AwsException("InvalidParameterValueException", "ResourceArn is required.", 400);
|
||||
}
|
||||
try {
|
||||
var arn = io.github.hectorvent.floci.core.common.AwsArnUtils.parse(resourceArn);
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
|
||||
if (!"memorydb".equals(arn.service()) || !currentRegion().equals(arn.region())
|
||||
|| !regionResolver.getAccountId().equals(arn.accountId())) {
|
||||
throw new IllegalArgumentException("ARN owner mismatch");
|
||||
@@ -647,11 +649,11 @@ public class MemoryDbService {
|
||||
}
|
||||
|
||||
private <V> java.util.Optional<V> resourceGet(StorageBackend<String, V> store, String name, String region) {
|
||||
var result = store.get(key(region, name));
|
||||
Optional<V> result = store.get(key(region, name));
|
||||
if (result.isPresent()) {
|
||||
return result;
|
||||
}
|
||||
var legacy = legacyGet(store, name, region);
|
||||
Optional<V> legacy = legacyGet(store, name, region);
|
||||
if (legacy.isPresent()) {
|
||||
setOwner(legacy.get(), region);
|
||||
store.put(key(region, name), legacy.get());
|
||||
|
||||
@@ -57,14 +57,14 @@ public class MskController {
|
||||
@GET
|
||||
@Path("/v1/clusters")
|
||||
public Response listClusters() {
|
||||
var clusters = mskService.listProvisionedClusters().stream().map(this::toClusterViewV1).toList();
|
||||
List<Map<String, Object>> clusters = mskService.listProvisionedClusters().stream().map(this::toClusterViewV1).toList();
|
||||
return Response.ok(Map.of("clusterInfoList", clusters)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/api/v2/clusters")
|
||||
public Response listClustersV2() {
|
||||
var clusters = mskService.listClusters().stream().map(this::toClusterViewV2).toList();
|
||||
List<Map<String, Object>> clusters = mskService.listClusters().stream().map(this::toClusterViewV2).toList();
|
||||
return Response.ok(Map.of("clusterInfoList", clusters)).build();
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ public class MskController {
|
||||
@QueryParam("nextToken") String nextToken) {
|
||||
PaginatedResult<MskConfiguration> result = mskService.listConfigurations(
|
||||
Pagination.parseMaxResults(maxResultsParam, "BadRequestException"), nextToken);
|
||||
var configurations = result.items().stream()
|
||||
List<Map<String, Object>> configurations = result.items().stream()
|
||||
.map(this::toConfigurationView)
|
||||
.toList();
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.msk;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -220,10 +224,10 @@ public class RedpandaManager {
|
||||
// Derive admin URL from the container
|
||||
String adminUrl;
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
var dockerClient = lifecycleManager.getDockerClient();
|
||||
var inspect = dockerClient.inspectContainerCmd(cluster.getContainerId()).exec();
|
||||
var bindings = inspect.getNetworkSettings().getPorts().getBindings();
|
||||
var binding = bindings.get(com.github.dockerjava.api.model.ExposedPort.tcp(ADMIN_PORT));
|
||||
DockerClient dockerClient = lifecycleManager.getDockerClient();
|
||||
InspectContainerResponse inspect = dockerClient.inspectContainerCmd(cluster.getContainerId()).exec();
|
||||
Map<ExposedPort, Ports.Binding[]> bindings = inspect.getNetworkSettings().getPorts().getBindings();
|
||||
Ports.Binding[] binding = bindings.get(ExposedPort.tcp(ADMIN_PORT));
|
||||
if (binding != null && binding.length > 0) {
|
||||
adminUrl = "http://localhost:" + binding[0].getHostPortSpec() + ADMIN_READY_PATH;
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -301,14 +302,14 @@ public class OamService {
|
||||
return true;
|
||||
}
|
||||
List<String> allowed = new ArrayList<>();
|
||||
var operators = condition.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> operators = condition.fields();
|
||||
while (operators.hasNext()) {
|
||||
Map.Entry<String, JsonNode> operator = operators.next();
|
||||
JsonNode entries = operator.getValue();
|
||||
if (!entries.isObject()) {
|
||||
return false;
|
||||
}
|
||||
var conditions = entries.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> conditions = entries.fields();
|
||||
while (conditions.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = conditions.next();
|
||||
if (!"oam:ResourceTypes".equalsIgnoreCase(entry.getKey())) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.pipes;
|
||||
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -160,7 +161,7 @@ public class PipesController {
|
||||
desiredState, currentState, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var pipesArray = response.putArray("Pipes");
|
||||
ArrayNode pipesArray = response.putArray("Pipes");
|
||||
for (Pipe pipe : pipes) {
|
||||
pipesArray.add(buildPipeListEntry(pipe));
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class PipesFilterMatcher {
|
||||
@@ -70,9 +72,9 @@ public class PipesFilterMatcher {
|
||||
if (!pattern.isObject()) {
|
||||
return false;
|
||||
}
|
||||
var fields = pattern.fields();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = pattern.fields();
|
||||
while (fields.hasNext()) {
|
||||
var field = fields.next();
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
String key = field.getKey();
|
||||
JsonNode patternValue = field.getValue();
|
||||
JsonNode actualValue = actual.path(key);
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.pipes;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
@@ -623,7 +624,7 @@ public class PipesPoller implements Resettable {
|
||||
}
|
||||
|
||||
private String bareArray(List<JsonNode> records) {
|
||||
var arr = objectMapper.createArrayNode();
|
||||
ArrayNode arr = objectMapper.createArrayNode();
|
||||
records.forEach(arr::add);
|
||||
return arr.toString();
|
||||
}
|
||||
@@ -688,7 +689,7 @@ public class PipesPoller implements Resettable {
|
||||
|
||||
private String wrapRecords(List<JsonNode> records) {
|
||||
try {
|
||||
var recordsArray = objectMapper.createArrayNode();
|
||||
ArrayNode recordsArray = objectMapper.createArrayNode();
|
||||
records.forEach(recordsArray::add);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.set("Records", recordsArray);
|
||||
@@ -778,14 +779,14 @@ public class PipesPoller implements Resettable {
|
||||
putKafkaBinaryField(node, "key", record.key());
|
||||
putKafkaBinaryField(node, "value", record.value());
|
||||
|
||||
var headersNode = node.putArray("headers");
|
||||
ArrayNode headersNode = node.putArray("headers");
|
||||
for (KafkaHeaderDto header : record.headers()) {
|
||||
ObjectNode headerNode = objectMapper.createObjectNode();
|
||||
byte[] headerValue = header.value();
|
||||
if (headerValue == null) {
|
||||
headerNode.putNull(header.key());
|
||||
} else {
|
||||
var values = headerNode.putArray(header.key());
|
||||
ArrayNode values = headerNode.putArray(header.key());
|
||||
for (byte b : headerValue) {
|
||||
values.add(b & 0xFF);
|
||||
}
|
||||
|
||||
+14
-13
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.resourceexplorer2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.resourceexplorer2.model.*;
|
||||
@@ -94,7 +95,7 @@ public class ResourceExplorer2Controller {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
Map<String, String> tags = parseTags(req);
|
||||
Index index = service.createIndex(region, tags);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("Arn", index.arn());
|
||||
result.put("CreatedAt", index.createdAt().toString());
|
||||
// Real AWS returns CREATING immediately; we store ACTIVE synchronously but the
|
||||
@@ -108,7 +109,7 @@ public class ResourceExplorer2Controller {
|
||||
public Response getIndex(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
Index index = service.getIndex(region);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("Arn", index.arn());
|
||||
result.put("CreatedAt", index.createdAt().toString());
|
||||
result.put("LastUpdatedAt", index.lastUpdatedAt().toString());
|
||||
@@ -129,7 +130,7 @@ public class ResourceExplorer2Controller {
|
||||
throw new AwsException("ValidationException", "Arn is required", 400);
|
||||
}
|
||||
Index deleted = service.deleteIndex(indexArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("Arn", deleted.arn());
|
||||
result.put("LastUpdatedAt", deleted.lastUpdatedAt().toString());
|
||||
result.put("State", deleted.state().name());
|
||||
@@ -165,7 +166,7 @@ public class ResourceExplorer2Controller {
|
||||
throw new AwsException("ValidationException", "Invalid index type: " + req.get("Type").asText(), 400);
|
||||
}
|
||||
Index index = service.updateIndexType(arn, type);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("Arn", index.arn());
|
||||
result.put("LastUpdatedAt", index.lastUpdatedAt().toString());
|
||||
result.put("State", index.state().name());
|
||||
@@ -184,7 +185,7 @@ public class ResourceExplorer2Controller {
|
||||
List<IncludedProperty> includedProperties = parseIncludedProperties(req);
|
||||
Map<String, String> tags = parseTags(req);
|
||||
View view = service.createView(region, viewName, scope, filters, includedProperties, tags);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.set("View", service.buildViewNode(view));
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
@@ -198,7 +199,7 @@ public class ResourceExplorer2Controller {
|
||||
throw new AwsException("ValidationException", "ViewArn is required", 400);
|
||||
}
|
||||
View view = service.getView(viewArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.set("View", service.buildViewNode(view));
|
||||
result.set("Tags", objectMapper.valueToTree(
|
||||
view.tags() != null ? view.tags() : Map.of()));
|
||||
@@ -214,7 +215,7 @@ public class ResourceExplorer2Controller {
|
||||
throw new AwsException("ValidationException", "ViewArn is required", 400);
|
||||
}
|
||||
service.deleteView(viewArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("ViewArn", viewArn);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
@@ -230,7 +231,7 @@ public class ResourceExplorer2Controller {
|
||||
SearchFilter filters = parseFilters(req);
|
||||
List<IncludedProperty> includedProperties = parseIncludedProperties(req);
|
||||
View view = service.updateView(viewArn, filters, includedProperties);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.set("View", service.buildViewNode(view));
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
@@ -261,7 +262,7 @@ public class ResourceExplorer2Controller {
|
||||
throw new AwsException("ValidationException", "ViewArn is required", 400);
|
||||
}
|
||||
service.associateDefaultView(regionResolver.resolveRegion(headers), viewArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("ViewArn", viewArn);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
@@ -277,7 +278,7 @@ public class ResourceExplorer2Controller {
|
||||
@Path("/GetDefaultView")
|
||||
public Response getDefaultView(@Context HttpHeaders headers) {
|
||||
String viewArn = service.getDefaultView(regionResolver.resolveRegion(headers));
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
if (viewArn != null) {
|
||||
result.put("ViewArn", viewArn);
|
||||
}
|
||||
@@ -377,7 +378,7 @@ public class ResourceExplorer2Controller {
|
||||
stringArray(req, "RegionList"),
|
||||
optString(req, "ViewName"),
|
||||
stringArray(req, "AggregatorRegions"));
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("TaskId", taskId);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
@@ -390,7 +391,7 @@ public class ResourceExplorer2Controller {
|
||||
? req.get("DeleteInAllRegions").asBoolean() : null;
|
||||
String taskId = service.deleteResourceExplorerSetup(
|
||||
deleteInAllRegions, stringArray(req, "RegionList"));
|
||||
var result = objectMapper.createObjectNode();
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.put("TaskId", taskId);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
@@ -442,7 +443,7 @@ public class ResourceExplorer2Controller {
|
||||
private List<IncludedProperty> parseIncludedProperties(JsonNode req) {
|
||||
List<IncludedProperty> includedProperties = new ArrayList<>();
|
||||
if (req.has("IncludedProperties") && req.get("IncludedProperties").isArray()) {
|
||||
for (var p : req.get("IncludedProperties")) {
|
||||
for (JsonNode p : req.get("IncludedProperties")) {
|
||||
includedProperties.add(new IncludedProperty(p.has("Name") ? p.get("Name").asText() : ""));
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1027,7 +1027,7 @@ public class ResourceExplorer2Service {
|
||||
if (includeTags && r.tags() != null && !r.tags().isEmpty()) {
|
||||
ObjectNode tagProp = objectMapper.createObjectNode();
|
||||
ArrayNode tagData = objectMapper.createArrayNode();
|
||||
for (var entry : r.tags().entrySet()) {
|
||||
for (Map.Entry<String, String> entry : r.tags().entrySet()) {
|
||||
ObjectNode tagEntry = objectMapper.createObjectNode();
|
||||
tagEntry.put("Key", entry.getKey());
|
||||
tagEntry.put("Value", entry.getValue());
|
||||
|
||||
+2
-2
@@ -41,7 +41,7 @@ public final class ResourceFilter {
|
||||
*/
|
||||
public static boolean matches(ExplorerResource resource, ParsedQuery query,
|
||||
Set<String> taggableResourceTypes) {
|
||||
for (var filter : query.filters()) {
|
||||
for (ParsedQuery.Filter filter : query.filters()) {
|
||||
boolean anyValueMatches = filter.values().stream()
|
||||
.anyMatch(v -> matchesValue(resource, filter.attribute(), v, taggableResourceTypes));
|
||||
if (filter.negated()) {
|
||||
@@ -63,7 +63,7 @@ public final class ResourceFilter {
|
||||
private static boolean matchesKeywords(ExplorerResource resource, List<ParsedQuery.Keyword> keywords) {
|
||||
boolean sawPositive = false;
|
||||
boolean anyPositiveMatched = false;
|
||||
for (var keyword : keywords) {
|
||||
for (ParsedQuery.Keyword keyword : keywords) {
|
||||
boolean matched = matchesKeyword(resource, keyword.value());
|
||||
if (keyword.negated()) {
|
||||
if (matched) {
|
||||
|
||||
+3
-1
@@ -10,6 +10,8 @@ import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* JSON 1.1 handler for Route 53 Resolver operations.
|
||||
* Dispatches {@code X-Amz-Target: Route53Resolver.*} actions to {@link Route53ResolverService}.
|
||||
@@ -106,7 +108,7 @@ public class Route53ResolverJsonHandler {
|
||||
|
||||
private Response handleGetFirewallDomainList(JsonNode request, String region) {
|
||||
String id = text(request, "FirewallDomainListId");
|
||||
var custom = service.getCustomFirewallDomainList(id);
|
||||
Optional<ObjectNode> custom = service.getCustomFirewallDomainList(id);
|
||||
if (custom.isPresent()) {
|
||||
return firewallDomainListResponse(custom.get());
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.rum;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -110,7 +111,7 @@ public class RumController {
|
||||
RumService.Page page = service.listAppMonitors(
|
||||
regionResolver.resolveRegion(headers), maxResults, nextToken);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
var summaries = response.putArray("AppMonitorSummaries");
|
||||
ArrayNode summaries = response.putArray("AppMonitorSummaries");
|
||||
for (AppMonitor monitor : page.monitors()) {
|
||||
ObjectNode summary = objectMapper.createObjectNode();
|
||||
summary.put("Created", monitor.getCreated());
|
||||
|
||||
Loaded 100 of 392 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user