You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by ma...@apache.org on 2026/09/17 20:59:53 UTC
(camel-karavan) 02/02: Fixes for Karavan 4.22.0
This is an automated email from the ASF dual-hosted git repository.
mgubaidullin pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-karavan.git
commit 1c8d25c4bd09c59573091391ccacae89beb9a889
Author: Marat Gubaidullin <ma...@talismancloud.io>
AuthorDate: Thu Sep 17 16:59:42 2026 -0400
Fixes for Karavan 4.22.0
---
.../org/apache/camel/karavan/KaravanConstants.java | 1 +
.../org/apache/camel/karavan/api/AuthResource.java | 2 +
.../apache/camel/karavan/api/ImagesResource.java | 19 +-
.../camel/karavan/api/InfrastructureResource.java | 19 +-
.../apache/camel/karavan/api/InternalResource.java | 14 +-
.../camel/karavan/api/ProjectFileResource.java | 17 +
.../camel/karavan/api/ProjectGitResource.java | 16 +
.../karavan/api/TokenAuthenticationMechanism.java | 2 +-
.../apache/camel/karavan/cache/AccessToken.java | 17 +
.../camel/karavan/cache/CamelStatusValue.java | 4 +-
.../apache/camel/karavan/cache/KaravanCache.java | 19 +-
.../apache/camel/karavan/cache/ProjectFolder.java | 8 +-
.../karavan/docker/DockerComposeConverter.java | 10 +
.../camel/karavan/docker/DockerForKaravan.java | 9 +-
.../apache/camel/karavan/docker/DockerService.java | 16 +-
.../apache/camel/karavan/docker/DockerUtils.java | 174 ++++++++-
.../karavan/kubernetes/KubernetesService.java | 99 ++++-
.../apache/camel/karavan/model/ContainerImage.java | 59 +--
.../apache/camel/karavan/model/DockerCompose.java | 3 +
.../camel/karavan/model/DockerComposeService.java | 49 +--
...ainerImage.java => DockerDeployDefinition.java} | 58 ++-
.../camel/karavan/model/DockerResourceLimits.java | 45 +++
.../model/DockerResourceSpecDefinition.java | 76 ++++
.../karavan/model/DockerResourcesDefinition.java | 62 ++++
.../org/apache/camel/karavan/model/GitConfig.java | 65 +---
.../karavan/service/CamelComponentService.java | 54 ++-
.../apache/camel/karavan/service/CodeService.java | 14 +-
.../camel/karavan/service/ComplexityService.java | 3 +-
.../apache/camel/karavan/service/GitService.java | 300 +++++----------
.../camel/karavan/service/GitServiceAuth.java | 134 +++++++
.../camel/karavan/service/ProjectService.java | 85 ++++-
.../karavan/service/RegistryImageService.java | 412 +++++++++++++++++++++
.../camel/karavan/service/RegistryService.java | 78 ++++
.../camel/karavan/util/CamelComponentMetadata.java | 108 ++++++
.../org/apache/camel/karavan/util/PathUtils.java | 32 ++
.../src/main/resources/application.properties | 2 +-
karavan-app/src/main/webui/package-lock.json | 17 -
.../webui/src/ui/page-project/ProjectPanel.tsx | 4 +-
38 files changed, 1603 insertions(+), 503 deletions(-)
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/KaravanConstants.java b/karavan-app/src/main/java/org/apache/camel/karavan/KaravanConstants.java
index fd29c53d..9ed4a257 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/KaravanConstants.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/KaravanConstants.java
@@ -43,6 +43,7 @@ public class KaravanConstants {
public static final String PRIVATE_KEY_SECRET_KEY = "private-key";
public static final String KNOWN_HOSTS_SECRET_KEY = "known-hosts";
public static final String KUBERNETES_YAML_FILENAME = "kubernetes.yaml";
+ public static final String DOCKER_COMPOSE_FILENAME = "docker-compose.yaml";
public static final String LABEL_KUBERNETES_RUNTIME = "app.kubernetes.io/runtime";
public static final String ANNOTATION_COMMIT = "jkube.eclipse.org/git-commit";
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/api/AuthResource.java b/karavan-app/src/main/java/org/apache/camel/karavan/api/AuthResource.java
index 6fe17e18..fa07031d 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/api/AuthResource.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/api/AuthResource.java
@@ -10,6 +10,7 @@ import org.apache.camel.karavan.cache.AccessUser;
import org.apache.camel.karavan.cache.KaravanCache;
import org.apache.camel.karavan.service.AuthService;
import org.eclipse.microprofile.config.ConfigProvider;
+import org.jboss.logging.Logger;
import java.util.Map;
@@ -19,6 +20,7 @@ import static org.apache.camel.karavan.service.AuthService.SESSION_MAX_AGE;
@Produces(MediaType.APPLICATION_JSON)
public class AuthResource extends AbstractApiResource {
+ private static final Logger LOGGER = Logger.getLogger(AuthResource.class.getName());
private static final String SESSION_ID = "sessionId";
private static final String CSRF = "csrf";
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/api/ImagesResource.java b/karavan-app/src/main/java/org/apache/camel/karavan/api/ImagesResource.java
index 28a0baeb..ba4f8835 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/api/ImagesResource.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/api/ImagesResource.java
@@ -27,13 +27,11 @@ import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.SecurityContext;
import org.apache.camel.karavan.docker.DockerService;
import org.apache.camel.karavan.model.ContainerImage;
-import org.apache.camel.karavan.model.RegistryConfig;
import org.apache.camel.karavan.service.ConfigService;
import org.apache.camel.karavan.service.ProjectService;
-import org.apache.camel.karavan.service.RegistryService;
+import org.apache.camel.karavan.service.RegistryImageService;
import org.jose4j.base64url.Base64;
-import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
@@ -46,7 +44,7 @@ public class ImagesResource extends AbstractApiResource {
DockerService dockerService;
@Inject
- RegistryService registryService;
+ RegistryImageService registryImageService;
@Inject
ProjectService projectService;
@@ -59,16 +57,9 @@ public class ImagesResource extends AbstractApiResource {
@Path("/project/{projectId}")
@Authenticated
public List<ContainerImage> getImagesForProject(@PathParam("projectId") String projectId) {
- if (ConfigService.inKubernetes()) {
- return List.of();
- } else {
- RegistryConfig registryConfig = registryService.getRegistryConfig();
- String pattern = registryConfig.getGroup() + "/" + projectId + ":";
- return dockerService.getImages()
- .stream().filter(s -> s.getTag().contains(pattern))
- .sorted(Comparator.comparing(ContainerImage::getCreated).reversed().thenComparing(ContainerImage::getTag))
- .toList();
- }
+ // Images are read from the container image registry with the OCI Distribution API, so the
+ // same list is returned in Docker and in Kubernetes
+ return registryImageService.getImagesForProject(projectId);
}
@POST
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/api/InfrastructureResource.java b/karavan-app/src/main/java/org/apache/camel/karavan/api/InfrastructureResource.java
index c55cddf1..05f184d4 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/api/InfrastructureResource.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/api/InfrastructureResource.java
@@ -62,9 +62,13 @@ public class InfrastructureResource {
@Path("/deployment")
@Authenticated
public List<DeploymentStatus> getAllDeploymentStatuses() throws Exception {
- return karavanCache.getDeploymentStatuses().stream()
- .sorted(Comparator.comparing(DeploymentStatus::getProjectId))
- .collect(Collectors.toList());
+ if (ConfigService.inKubernetes()) {
+ return karavanCache.getDeploymentStatuses().stream()
+ .sorted(Comparator.comparing(DeploymentStatus::getProjectId))
+ .collect(Collectors.toList());
+ } else {
+ return List.of();
+ }
}
@GET
@@ -72,9 +76,13 @@ public class InfrastructureResource {
@Path("/deployment/{env}")
@Authenticated
public List<DeploymentStatus> getDeploymentStatusesByEnv(@PathParam("env") String env) throws Exception {
- return karavanCache.getDeploymentStatuses(env).stream()
+ if (ConfigService.inKubernetes()) {
+ return karavanCache.getDeploymentStatuses(env).stream()
.sorted(Comparator.comparing(DeploymentStatus::getProjectId))
.collect(Collectors.toList());
+ } else {
+ return List.of();
+ }
}
@POST
@@ -96,6 +104,7 @@ public class InfrastructureResource {
if (resources == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Resource file " + KUBERNETES_YAML_FILENAME + " not found").build();
}
+ kubernetesService.startDeployment(resources.getCode(), Map.of(LABEL_TYPE, ContainerType.packaged.name()));
try {
kubernetesService.startDeployment(resources.getCode(), Map.of(LABEL_TYPE, ContainerType.packaged.name()));
} catch (IllegalArgumentException e) {
@@ -186,4 +195,4 @@ public class InfrastructureResource {
return Response.noContent().build();
}
}
-}
\ No newline at end of file
+}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/api/InternalResource.java b/karavan-app/src/main/java/org/apache/camel/karavan/api/InternalResource.java
index cf814f4f..51cc4901 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/api/InternalResource.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/api/InternalResource.java
@@ -52,10 +52,9 @@ public class InternalResource {
authService.validateSession(sessionId);
return getProjectFilesZipResponse(projectId, null);
} catch (Exception e) {
- LOGGER.error("Error retrieving files for project: " + projectId, e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
- .entity(e.getMessage())
- .build();
+ var message = "Error retrieving files for project " + projectId + ": " + e.getMessage();
+ LOGGER.error(message);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message).build();
} finally {
authService.invalidateSession(sessionId);
}
@@ -72,10 +71,9 @@ public class InternalResource {
return getProjectFilesZipResponse(projectId, filename);
} catch (Exception e) {
- LOGGER.error("Error retrieving file " + filename + " for project: " + projectId, e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
- .entity(e.getMessage())
- .build();
+ var message = "Error retrieving file " + filename + " for project " + projectId + ": " + e.getMessage();
+ LOGGER.error(message);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message).build();
}
}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectFileResource.java b/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectFileResource.java
index 43b91ed7..561c7a00 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectFileResource.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectFileResource.java
@@ -59,6 +59,23 @@ public class ProjectFileResource {
}
}
+ @GET
+ @Authenticated
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/pattern/{projectId}")
+ public Response getProjectFilesByPattern(@PathParam("projectId") String projectId, @QueryParam("pattern") String pattern) {
+ try {
+ PathUtils.validateProjectId(projectId);
+ var files = karavanCache.getProjectFilesByPattern(projectId, pattern).stream()
+ .filter(Objects::nonNull)
+ .sorted(Comparator.comparing(ProjectFile::getName))
+ .collect(Collectors.toList());
+ return Response.ok(files).build();
+ } catch (IllegalArgumentException e) {
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
+ }
+ }
+
@GET
@Authenticated
@Produces(MediaType.APPLICATION_JSON)
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectGitResource.java b/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectGitResource.java
index 9d38dfe8..d7ca982d 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectGitResource.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectGitResource.java
@@ -86,4 +86,20 @@ public class ProjectGitResource extends AbstractApiResource {
}
}
+
+ @PATCH
+ @Produces(MediaType.APPLICATION_JSON)
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Path("/{projectId}/{commitId}")
+ @Authenticated
+ public Response revertToCommit(@PathParam("projectId") String projectId, @PathParam("commitId") String commitId) {
+ try {
+ projectService.revertProjectToCommit(projectId, commitId);
+ return Response.ok().build();
+ } catch (Exception e) {
+ LOGGER.error(e.getMessage());
+ return Response.serverError().entity(e.getMessage()).build();
+ }
+
+ }
}
\ No newline at end of file
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/api/TokenAuthenticationMechanism.java b/karavan-app/src/main/java/org/apache/camel/karavan/api/TokenAuthenticationMechanism.java
index 8bc069e5..2e5c39b5 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/api/TokenAuthenticationMechanism.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/api/TokenAuthenticationMechanism.java
@@ -65,7 +65,7 @@ public class TokenAuthenticationMechanism implements HttpAuthenticationMechanism
.addAttribute("clientName", metadata.clientName())
.setAnonymous(false);
- LOGGER.infof("Trace: Authenticated", metadata.clientName(), metadata.ownerName());
+ LOGGER.infof("Trace: Authenticated MCP agent [%s] owned by [%s]", metadata.clientName(), metadata.ownerName());
return Uni.createFrom().item(builder.build());
} catch (Exception e) {
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/cache/AccessToken.java b/karavan-app/src/main/java/org/apache/camel/karavan/cache/AccessToken.java
index 60e14176..4514b40f 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/cache/AccessToken.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/cache/AccessToken.java
@@ -12,7 +12,24 @@ public record AccessToken(
Instant expiresAt
) {
+ /**
+ * Checks if the token has surpassed its expiration timestamp.
+ */
public boolean isExpired() {
return expiresAt != null && Instant.now().isAfter(expiresAt);
}
+
+ /**
+ * Checks whether the external agent has authorization to access a specific project.
+ * Supports a wildcard "*" for unrestricted developer-level access.
+ */
+ public boolean hasProjectAccess(String projectId) {
+ if (isExpired()) {
+ return false;
+ }
+ if (allowedProjectIds == null || allowedProjectIds.isEmpty()) {
+ return false;
+ }
+ return allowedProjectIds.contains("*") || allowedProjectIds.contains(projectId);
+ }
}
\ No newline at end of file
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/cache/CamelStatusValue.java b/karavan-app/src/main/java/org/apache/camel/karavan/cache/CamelStatusValue.java
index b4869bda..4274d9fc 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/cache/CamelStatusValue.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/cache/CamelStatusValue.java
@@ -33,7 +33,9 @@ public class CamelStatusValue {
processor,
consumer,
producer,
- platform_http
+ platform_http,
+ errors,
+ activity
}
Name name;
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/cache/KaravanCache.java b/karavan-app/src/main/java/org/apache/camel/karavan/cache/KaravanCache.java
index dc7cf257..f4914a55 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/cache/KaravanCache.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/cache/KaravanCache.java
@@ -22,6 +22,7 @@ import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import org.apache.camel.karavan.model.ActivityUser;
import org.apache.camel.karavan.service.AuthService;
+import org.apache.camel.karavan.util.PathUtils;
import java.time.Instant;
import java.util.*;
@@ -160,6 +161,18 @@ public class KaravanCache {
ProjectFile::copy);
}
+ /**
+ * Files of a project whose name matches a glob like {@code *-task-template.md}. Keeps the large files of a
+ * project (agent prompts, organization context) out of the response when only a few small ones are wanted.
+ */
+ public List<ProjectFile> getProjectFilesByPattern(String projectId, String pattern) {
+ var matcher = PathUtils.compileFileNameGlob(pattern);
+ return query(files,
+ f -> Objects.equals(f.getProjectId(), projectId) && f.getName() != null
+ && matcher.matcher(f.getName()).matches(),
+ ProjectFile::copy);
+ }
+
public List<ProjectFile> getProjectFilesByName(String filename) {
return query(files, f -> Objects.equals(f.getName(), filename), ProjectFile::copy);
}
@@ -280,7 +293,9 @@ public class KaravanCache {
}
public PodContainerStatus getPodContainerStatus(String containerName, String env) {
- return getPodContainerStatusesByProject(env).stream().filter(el -> Objects.equals(el.getContainerName(), containerName)).findFirst().orElse(null);
+ return queryFirst(podContainerStatuses,
+ status -> Objects.equals(status.getContainerName(), containerName) && Objects.equals(status.getEnv(), env),
+ PodContainerStatus::copy);
}
public PodContainerStatus getPodContainerStatus(String key) {
@@ -356,7 +371,7 @@ public class KaravanCache {
&& Objects.equals(status.getEnv(), env);
});
}
-
+
public void deleteAllCamelStatuses() {
camelStatuses.clear();
}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/cache/ProjectFolder.java b/karavan-app/src/main/java/org/apache/camel/karavan/cache/ProjectFolder.java
index 123b84f7..3f7b1b94 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/cache/ProjectFolder.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/cache/ProjectFolder.java
@@ -98,13 +98,9 @@ public class ProjectFolder {
this.type = type;
}
+
public static List<String> getBuildInNames(){
- return List.of(
- Type.configuration.name(),
- Type.kamelets.name(),
- Type.templates.name(),
- Type.documentation.name()
- );
+ return Arrays.stream(Type.values()).filter(v -> !Type.integration.equals(v)).map(Type::name).toList();
}
@Override
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerComposeConverter.java b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerComposeConverter.java
index 40311d0e..5637e2e5 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerComposeConverter.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerComposeConverter.java
@@ -22,12 +22,14 @@ import io.vertx.core.json.JsonObject;
import org.apache.camel.karavan.model.DockerCompose;
import org.apache.camel.karavan.model.DockerComposeService;
import org.apache.camel.karavan.model.DockerVolumeDefinition;
+import org.jboss.logging.Logger;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.*;
import org.yaml.snakeyaml.representer.Representer;
+import java.util.List;
import java.util.Map;
import static com.github.dockerjava.api.model.MountType.BIND;
@@ -38,6 +40,11 @@ public class DockerComposeConverter {
private static final String ENVIRONMENT = "environment";
private static final String LABELS = "labels";
private static final String VOLUMES = "volumes";
+ // Resource keys of the legacy Compose file formats, superseded by deploy.resources
+ private static final List<String> LEGACY_RESOURCE_KEYS = List.of("cpus", "cpu_percent", "cpu_shares",
+ "mem_limit", "mem_reservation", "memswap_limit");
+
+ private static final Logger LOGGER = Logger.getLogger(DockerComposeConverter.class.getName());
public static DockerCompose fromCode(String code) {
Yaml yaml = new Yaml();
@@ -111,6 +118,9 @@ public class DockerComposeConverter {
service.put(VOLUMES, volumes);
}
+ LEGACY_RESOURCE_KEYS.stream().filter(service::containsKey).forEach(key ->
+ LOGGER.warnf("Service %s: '%s' belongs to a legacy compose format and is ignored, declare it under deploy.resources instead", name, key));
+
DockerComposeService ds = service.mapTo(DockerComposeService.class);
if (ds.getContainer_name() == null) {
ds.setContainer_name(name);
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForKaravan.java b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForKaravan.java
index d18f623a..1908c0a3 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForKaravan.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForKaravan.java
@@ -25,6 +25,7 @@ import jakarta.inject.Inject;
import org.apache.camel.karavan.cache.ContainerType;
import org.apache.camel.karavan.cache.ProjectFolder;
import org.apache.camel.karavan.model.DockerComposeService;
+import org.apache.camel.karavan.model.DockerResourceLimits;
import org.apache.camel.karavan.model.DockerVolumeDefinition;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.jboss.logging.Logger;
@@ -32,7 +33,6 @@ import org.jboss.logging.Logger;
import java.util.*;
import static org.apache.camel.karavan.KaravanConstants.*;
-import static org.apache.camel.karavan.service.CodeService.BUILD_SCRIPT_FILENAME;
@ApplicationScoped
public class DockerForKaravan {
@@ -88,17 +88,16 @@ public class DockerForKaravan {
env, compose.getPortsMap(), healthCheck,
containerLabels,
compose.getVolumes(), null, RestartPolicy.noRestart(), DockerService.PULL_IMAGE.ifNotExists,
- compose.getCpus(), compose.getCpu_percent(), compose.getMem_limit(), compose.getMem_reservation(), compose.getCommand());
+ DockerResourceLimits.from(compose), compose.getCommand());
}
- public void runBuildProject(ProjectFolder projectFolder, String script, DockerComposeService compose, Map<String, String> sshFiles, String tag) throws Exception {
+ public void runBuildProject(ProjectFolder projectFolder, DockerComposeService compose, Map<String, String> sshFiles, String tag) throws Exception {
String containerName = projectFolder.getProjectId() + BUILDER_SUFFIX;
dockerService.deleteContainer(containerName);
if (createM2.orElse(false)) {
compose.getVolumes().add(new DockerVolumeDefinition(MountType.VOLUME.name(), projectFolder.getProjectId() + "-build-m2-repository", "/karavan/.m2/repository"));
}
Container c = createBuildContainer(containerName, projectFolder, compose.getEnvironmentList(), compose.getVolumes(), tag);
- dockerService.copyFileToContainer(c.getId(), "/karavan/builder", BUILD_SCRIPT_FILENAME, script, 0755);
sshFiles.forEach((name, text) -> {
dockerService.copyFileToContainer(c.getId(), "/karavan/.ssh", name, text, 0600);
});
@@ -116,7 +115,7 @@ public class DockerForKaravan {
LABEL_TAG, tag
),
volumes, null, RestartPolicy.noRestart(), DockerService.PULL_IMAGE.ifNotExists,
- null, null, null, null,
+ DockerResourceLimits.NONE,
"/karavan/builder/build.sh");
}
}
\ No newline at end of file
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerService.java b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerService.java
index aab6f863..ab6418a5 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerService.java
@@ -22,13 +22,13 @@ import jakarta.inject.Inject;
import org.apache.camel.karavan.cache.ContainerType;
import org.apache.camel.karavan.model.ContainerImage;
import org.apache.camel.karavan.model.DockerComposeService;
+import org.apache.camel.karavan.model.DockerResourceLimits;
import org.apache.camel.karavan.model.DockerVolumeDefinition;
import org.apache.camel.karavan.service.CodeService;
import org.apache.camel.karavan.service.ConfigService;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.math.NumberUtils;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.health.Readiness;
import org.jboss.logging.Logger;
@@ -186,7 +186,7 @@ public class DockerService {
return createContainer(compose.getContainer_name(), compose.getImage(),
env, compose.getPortsMap(), healthCheck, labels, compose.getVolumes(), networkName, restartPolicy, pullImage,
- compose.getCpus(), compose.getCpu_percent(), compose.getMem_limit(), compose.getMem_reservation(), compose.getCommand());
+ DockerResourceLimits.from(compose), compose.getCommand());
} else {
return containers.getFirst();
}
@@ -212,7 +212,7 @@ public class DockerService {
public Container createContainer(String name, String image, List<String> env, Map<Integer, Integer> ports,
HealthCheck healthCheck, Map<String, String> labels,
List<DockerVolumeDefinition> volumes, String network, RestartPolicy restartPolicy,
- PULL_IMAGE pullImage, String cpus, String cpu_percent, String mem_limit, String mem_reservation,
+ PULL_IMAGE pullImage, DockerResourceLimits resourceLimits,
String dockerCommand) throws InterruptedException {
if (Objects.equals(labels.get(LABEL_TYPE), ContainerType.devmode.name()) || Objects.equals(labels.get(LABEL_TYPE), ContainerType.build.name())) {
@@ -234,11 +234,11 @@ public class DockerService {
}
if (dockerCommand != null) createContainerCmd.withCmd("/bin/sh", "-c", dockerCommand);
- createContainerCmd.withHostConfig(new HostConfig()
+ HostConfig hostConfig = new HostConfig()
.withRestartPolicy(restartPolicy).withPortBindings(portBindings).withMounts(mounts)
- .withMemory(DockerUtils.parseMemory(mem_limit)).withMemoryReservation(DockerUtils.parseMemory(mem_reservation))
- .withCpuPercent(NumberUtils.toLong(cpu_percent)).withNanoCPUs(NumberUtils.toLong(cpus))
- .withNetworkMode(network != null ? network : networkName));
+ .withNetworkMode(network != null ? network : networkName);
+ DockerUtils.applyResourceLimits(hostConfig, resourceLimits);
+ createContainerCmd.withHostConfig(hostConfig);
CreateContainerResponse response = createContainerCmd.exec();
return getContainer(response.getId());
@@ -428,7 +428,7 @@ public class DockerService {
public List<ContainerImage> getImages() {
return getDockerClient().listImagesCmd().withShowAll(true).exec().stream()
.filter(i -> i.getRepoTags() != null && i.getRepoTags().length > 0)
- .map(i -> new ContainerImage(i.getId(), i.getRepoTags()[0], i.getCreated(), i.getSize()))
+ .map(i -> new ContainerImage(i.getId(), List.of(i.getRepoTags()), i.getLabels(), i.getCreated(), i.getSize()))
.toList();
}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerUtils.java b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerUtils.java
index 037dc7b3..24fda51c 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerUtils.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerUtils.java
@@ -22,6 +22,8 @@ import org.apache.camel.karavan.cache.ContainerPort;
import org.apache.camel.karavan.cache.ContainerType;
import org.apache.camel.karavan.cache.PodContainerStatus;
import org.apache.camel.karavan.model.DockerHealthCheckDefinition;
+import org.apache.camel.karavan.model.DockerResourceLimits;
+import org.jboss.logging.Logger;
import java.text.DecimalFormat;
import java.time.Duration;
@@ -35,34 +37,182 @@ import static org.apache.camel.karavan.KaravanConstants.*;
public class DockerUtils {
+ private static final Logger LOGGER = Logger.getLogger(DockerUtils.class.getName());
+
protected static final DecimalFormat formatCpu = new DecimalFormat("0.00");
protected static final DecimalFormat formatMiB = new DecimalFormat("0.0");
protected static final DecimalFormat formatGiB = new DecimalFormat("0.00");
protected static final Map<String, Tuple2<Long, Long>> previousStats = new ConcurrentHashMap<>();
- private static final Map<String, Long> UNIT_MULTIPLIERS = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);;
+ private static final Map<String, Long> UNIT_MULTIPLIERS = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
static {
+ UNIT_MULTIPLIERS.put("", 1L);
UNIT_MULTIPLIERS.put("b", 1L);
UNIT_MULTIPLIERS.put("k", 1024L);
+ UNIT_MULTIPLIERS.put("kb", 1024L);
+ UNIT_MULTIPLIERS.put("kib", 1024L);
UNIT_MULTIPLIERS.put("m", 1024L * 1024);
+ UNIT_MULTIPLIERS.put("mb", 1024L * 1024);
+ UNIT_MULTIPLIERS.put("mib", 1024L * 1024);
UNIT_MULTIPLIERS.put("g", 1024L * 1024 * 1024);
- // Add more units if needed
+ UNIT_MULTIPLIERS.put("gb", 1024L * 1024 * 1024);
+ UNIT_MULTIPLIERS.put("gib", 1024L * 1024 * 1024);
+ UNIT_MULTIPLIERS.put("t", 1024L * 1024 * 1024 * 1024);
+ UNIT_MULTIPLIERS.put("tb", 1024L * 1024 * 1024 * 1024);
+ UNIT_MULTIPLIERS.put("tib", 1024L * 1024 * 1024 * 1024);
}
+ private static final Pattern MEMORY_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)?)\\s*([a-zA-Z]*)$");
+
+ // Docker refuses a memory limit below 6MiB.
+ static final long MIN_MEMORY = 6L * 1024 * 1024;
+ static final long NANO = 1_000_000_000L;
+ // 1e6 nanoCPUs (0.001 CPU) is the smallest value the Daemon accepts.
+ static final long MIN_NANO_CPUS = 1_000_000L;
+ // Relative CPU weight the Linux scheduler gives to a container asking for a single CPU.
+ static final int CPU_SHARES_PER_CPU = 1024;
+ // Relative CPU weight accepted by the Linux scheduler.
+ static final int MIN_CPU_SHARES = 2;
+ static final int MAX_CPU_SHARES = 262_144;
+
+ /**
+ * Parses a Compose byte value ("512m", "1gb", "1024") into bytes. Compose byte units are
+ * powers of 1024, so "1kb" and "1kib" are both 1024 bytes.
+ */
static Long parseMemory(String memory) {
+ if (memory == null || memory.isBlank()) {
+ return null;
+ }
+ var matcher = MEMORY_PATTERN.matcher(memory.trim());
+ if (!matcher.matches()) {
+ throw new IllegalArgumentException("Invalid memory value: " + memory);
+ }
+ double numericValue = Double.parseDouble(matcher.group(1));
+ Long multiplier = UNIT_MULTIPLIERS.get(matcher.group(2));
+ if (multiplier == null) {
+ throw new IllegalArgumentException("Invalid unit in memory: " + matcher.group(2));
+ }
+ return (long) (numericValue * multiplier);
+ }
+
+ /**
+ * Parses a Compose {@code cpus} value: a fractional number of CPUs, i.e. "1.5".
+ */
+ static Double parseCpus(String key, String cpus) {
+ if (cpus == null || cpus.isBlank()) {
+ return null;
+ }
+ double value;
+ try {
+ value = Double.parseDouble(cpus.trim());
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid " + key + " value: " + cpus);
+ }
+ return value > 0 ? value : null;
+ }
+
+ /**
+ * Converts a Compose {@code cpus} value into nanoCPUs, which is what the Docker Daemon expects.
+ */
+ static Long parseNanoCpus(String key, String cpus) {
+ Double value = parseCpus(key, cpus);
+ if (value == null) {
+ return null;
+ }
+ long nanoCpus = Math.round(value * NANO);
+ if (nanoCpus < MIN_NANO_CPUS) {
+ LOGGER.warnf("%s %s is below the minimum supported by Docker, using %s nanoCPUs", key, cpus, MIN_NANO_CPUS);
+ return MIN_NANO_CPUS;
+ }
+ return nanoCpus;
+ }
+
+ /**
+ * A CPU reservation cannot be granted by a standalone Daemon, the closest it offers is the
+ * relative CPU weight, which is what Compose itself falls back to. One CPU is 1024 shares.
+ */
+ static Integer toCpuShares(double cpus) {
+ long shares = Math.round(cpus * CPU_SHARES_PER_CPU);
+ if (shares < MIN_CPU_SHARES) {
+ return MIN_CPU_SHARES;
+ }
+ if (shares > MAX_CPU_SHARES) {
+ return MAX_CPU_SHARES;
+ }
+ return (int) shares;
+ }
- if (memory != null && !memory.isEmpty()) {
- memory = memory.trim();
- String numericPart = memory.replaceAll("[^\\d.]", "");
- double numericValue = Double.parseDouble(numericPart);
- String unitPart = memory.replaceAll("[\\d.]", "").toLowerCase();
- Long multiplier = UNIT_MULTIPLIERS.get(unitPart);
- if (multiplier == null) {
- throw new IllegalArgumentException("Invalid unit in memory: " + unitPart);
+ /**
+ * Parses a Compose {@code pids} limit. {@code -1} means unlimited.
+ */
+ static Long parsePidsLimit(String pids) {
+ if (pids == null || pids.isBlank()) {
+ return null;
+ }
+ long value;
+ try {
+ value = Long.parseLong(pids.trim());
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid pids value: " + pids);
+ }
+ if (value < 0) {
+ return -1L; // unlimited
+ }
+ return value;
+ }
+
+ /**
+ * Applies the {@code deploy.resources} limits and reservations to the HostConfig so that the
+ * Daemon actually enforces them. Values that are not set are left untouched instead of being
+ * sent as 0, which the Daemon reads as "no limit".
+ */
+ public static void applyResourceLimits(HostConfig hostConfig, DockerResourceLimits limits) {
+ if (limits == null) {
+ return;
+ }
+
+ Long memory = parseMemory(limits.memLimit());
+ if (memory != null && memory > 0) {
+ if (memory < MIN_MEMORY) {
+ LOGGER.warnf("memory limit %s is below the minimum supported by Docker, using %s bytes", limits.memLimit(), MIN_MEMORY);
+ memory = MIN_MEMORY;
}
- return (long) (numericValue * multiplier);
+ hostConfig.withMemory(memory);
+ // Without an explicit swap limit the Daemon grants twice the memory limit as swap,
+ // which lets the container exceed the configured limit. Pin swap to the limit.
+ hostConfig.withMemorySwap(memory);
+ } else {
+ memory = null;
+ }
+
+ Long reservation = parseMemory(limits.memReservation());
+ if (reservation != null && reservation > 0) {
+ if (memory != null && reservation > memory) {
+ LOGGER.warnf("memory reservation %s is greater than the memory limit, using the limit", limits.memReservation());
+ reservation = memory;
+ }
+ hostConfig.withMemoryReservation(reservation);
+ }
+
+ Double cpuLimit = parseCpus("cpus limit", limits.cpuLimit());
+ Long nanoCpus = parseNanoCpus("cpus limit", limits.cpuLimit());
+ if (nanoCpus != null) {
+ hostConfig.withNanoCPUs(nanoCpus);
+ }
+
+ Double cpuReservation = parseCpus("cpus reservation", limits.cpuReservation());
+ if (cpuReservation != null) {
+ if (cpuLimit != null && cpuReservation > cpuLimit) {
+ LOGGER.warnf("cpus reservation %s is greater than the cpus limit, using the limit", limits.cpuReservation());
+ cpuReservation = cpuLimit;
+ }
+ hostConfig.withCpuShares(toCpuShares(cpuReservation));
+ }
+
+ Long pidsLimit = parsePidsLimit(limits.pidsLimit());
+ if (pidsLimit != null && pidsLimit != 0) {
+ hostConfig.withPidsLimit(pidsLimit);
}
- return null;
}
static HealthCheck getHealthCheck(DockerHealthCheckDefinition config) {
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/KubernetesService.java b/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/KubernetesService.java
index b11ecb2a..c00840af 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/KubernetesService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/KubernetesService.java
@@ -20,6 +20,7 @@ import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
+import io.fabric8.kubernetes.client.dsl.ExecWatch;
import io.fabric8.kubernetes.client.dsl.LogWatch;
import io.fabric8.kubernetes.client.utils.Serialization;
import io.quarkus.runtime.LaunchMode;
@@ -27,17 +28,16 @@ import io.smallrye.mutiny.tuples.Tuple2;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Default;
import jakarta.enterprise.inject.Produces;
-import jakarta.inject.Inject;
import org.apache.camel.karavan.KaravanConstants;
import org.apache.camel.karavan.cache.ContainerType;
import org.apache.camel.karavan.model.KubernetesConfigMap;
import org.apache.camel.karavan.model.KubernetesSecret;
import org.apache.camel.karavan.model.PodEvent;
-import org.apache.camel.karavan.service.CodeService;
import org.apache.camel.karavan.service.ConfigService;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.jboss.logging.Logger;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
@@ -67,9 +67,6 @@ public class KubernetesService {
@ConfigProperty(name = "karavan.environment", defaultValue = KaravanConstants.DEV)
private String environment;
- @Inject
- CodeService codeService;
-
private String namespace;
@Produces
@@ -187,7 +184,6 @@ public class KubernetesService {
.withPorts(port, observabilityPort)
.withImagePullPolicy(devmodeImagePullPolicy.orElse("IfNotPresent"))
.withEnv(pod.getSpec().getContainers().getFirst().getEnv())
-// .withCommand("/bin/sh", "-c", "/karavan/builder/build.sh")
.withVolumeMounts(volumeMounts)
.build();
@@ -196,17 +192,17 @@ public class KubernetesService {
volumes.add(new VolumeBuilder().withName(BUILD_DOCKER_CONFIG_SECRET)
.withSecret(new SecretVolumeSourceBuilder().withSecretName(BUILD_DOCKER_CONFIG_SECRET).withItems(
new KeyToPathBuilder().withKey(".dockerconfigjson").withPath("config.json").build()
- ).withDefaultMode(511).build()).build());
+ ).withDefaultMode(600).build()).build());
}
if (privateKeyPath.isPresent()) {
volumes.add(new VolumeBuilder().withName(PRIVATE_KEY_SECRET_KEY)
.withSecret(new SecretVolumeSourceBuilder().withSecretName(secretName).withItems(
new KeyToPathBuilder().withKey(PRIVATE_KEY_SECRET_KEY).withPath("id_rsa").build()
- ).withDefaultMode(511).build()).build());
+ ).withDefaultMode(600).build()).build());
volumes.add(new VolumeBuilder().withName(KNOWN_HOSTS_SECRET_KEY)
.withSecret(new SecretVolumeSourceBuilder().withSecretName(secretName).withItems(
new KeyToPathBuilder().withKey(KNOWN_HOSTS_SECRET_KEY).withPath("known_hosts").build()
- ).withDefaultMode(511).build()).build());
+ ).withDefaultMode(600).build()).build());
}
PodSpec spec = new PodSpecBuilder()
@@ -285,7 +281,6 @@ public class KubernetesService {
putLabels(template.getMetadata(), labels);
}
}
- // Pin the namespace: a resource must never be applied outside of Karavan's namespace
item.getMetadata().setNamespace(getNamespace());
client.resource(item).inNamespace(getNamespace()).serverSideApply();
});
@@ -652,6 +647,51 @@ public class KubernetesService {
return null;
}
+ /**
+ * Contents of the `kubernetes.io/dockerconfigjson` pull secrets available to Talisman: the ones
+ * referenced by this pod and its ServiceAccount, the builder secret, and any other docker config
+ * secret of the namespace as a fallback. Legacy `.dockercfg` payloads are wrapped in `auths`.
+ */
+ public List<String> getDockerConfigJsons() {
+ List<String> result = new ArrayList<>();
+ try (KubernetesClient client = kubernetesClient()) {
+ Set<String> names = new LinkedHashSet<>();
+ String podName = System.getenv("HOSTNAME");
+ Pod pod = podName != null ? client.pods().inNamespace(getNamespace()).withName(podName).get() : null;
+ if (pod != null && pod.getSpec() != null) {
+ if (pod.getSpec().getImagePullSecrets() != null) {
+ pod.getSpec().getImagePullSecrets().forEach(ref -> names.add(ref.getName()));
+ }
+ String serviceAccountName = pod.getSpec().getServiceAccountName();
+ if (serviceAccountName != null) {
+ ServiceAccount serviceAccount = client.serviceAccounts().inNamespace(getNamespace()).withName(serviceAccountName).get();
+ if (serviceAccount != null && serviceAccount.getImagePullSecrets() != null) {
+ serviceAccount.getImagePullSecrets().forEach(ref -> names.add(ref.getName()));
+ }
+ }
+ }
+ names.add(BUILD_DOCKER_CONFIG_SECRET);
+ client.secrets().inNamespace(getNamespace()).list().getItems().stream()
+ .filter(secret -> Objects.equals(secret.getType(), "kubernetes.io/dockerconfigjson"))
+ .forEach(secret -> names.add(secret.getMetadata().getName()));
+ for (String name : names) {
+ Secret secret = client.secrets().inNamespace(getNamespace()).withName(name).get();
+ Map<String, String> data = secret != null ? secret.getData() : null;
+ if (data == null) {
+ continue;
+ }
+ if (data.get(".dockerconfigjson") != null) {
+ result.add(decodeSecret(data.get(".dockerconfigjson")));
+ } else if (data.get(".dockercfg") != null) {
+ result.add("{\"auths\":" + decodeSecret(data.get(".dockercfg")) + "}");
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.warn("Failed to read image pull secrets: " + e.getMessage());
+ }
+ return result;
+ }
+
public ConfigMap getConfigMap(String name) {
try (KubernetesClient client = kubernetesClient()) {
return client.configMaps().inNamespace(getNamespace()).withName(name).get();
@@ -828,4 +868,43 @@ public class KubernetesService {
}
return list;
}
+
+ public void execCommandInDeployment(String deploymentName, String command) {
+ try (KubernetesClient client = kubernetesClient()) {
+ Deployment deployment = client.apps().deployments().inNamespace(getNamespace()).withName(deploymentName).get();
+
+ if (deployment != null && deployment.getSpec().getSelector() != null) {
+ Map<String, String> matchLabels = deployment.getSpec().getSelector().getMatchLabels();
+ List<Pod> pods = client.pods().inNamespace(getNamespace()).withLabels(matchLabels).list().getItems();
+
+ if (!pods.isEmpty()) {
+ Pod pod = pods.getFirst();
+ String podName = pod.getMetadata().getName();
+ String containerName = pod.getSpec().getContainers().getFirst().getName();
+
+ LOGGER.info("Executing command in pod " + podName + " (container: " + containerName + ")");
+
+ try (ExecWatch watch = client.pods().inNamespace(getNamespace()).withName(podName)
+ .inContainer(containerName)
+ .writingOutput(OutputStream.nullOutputStream())
+ .writingError(OutputStream.nullOutputStream())
+ .exec("sh", "-c", command)) {
+
+ // Block the thread until the command finishes (or times out after 30s)
+ // This keeps the WebSocket open long enough for the command to run.
+ watch.exitCode().get(30, TimeUnit.SECONDS);
+
+ } catch (Exception e) {
+ LOGGER.error("Exec failed or timed out: " + e.getMessage());
+ }
+ } else {
+ LOGGER.warn("No pods found for deployment: " + deploymentName);
+ }
+ } else {
+ LOGGER.warn("Deployment not found or has no selector: " + deploymentName);
+ }
+ } catch (Exception e) {
+ LOGGER.error("Error executing command in container for deployment " + deploymentName + ": " + e.getMessage(), e);
+ }
+ }
}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/ContainerImage.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/ContainerImage.java
index 25966f40..8ee7f6dc 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/model/ContainerImage.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/ContainerImage.java
@@ -17,52 +17,13 @@
package org.apache.camel.karavan.model;
-public class ContainerImage {
-
- private String id;
- private String tag;
- private Long created;
- private Long size;
-
- public ContainerImage() {
- }
-
- public ContainerImage(String id, String tag, Long created, Long size) {
- this.id = id;
- this.tag = tag;
- this.created = created;
- this.size = size;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getTag() {
- return tag;
- }
-
- public void setTag(String tag) {
- this.tag = tag;
- }
-
- public Long getCreated() {
- return created;
- }
-
- public void setCreated(Long created) {
- this.created = created;
- }
-
- public Long getSize() {
- return size;
- }
-
- public void setSize(Long size) {
- this.size = size;
- }
-}
\ No newline at end of file
+import java.util.List;
+import java.util.Map;
+
+public record ContainerImage(
+ String id,
+ List<String> tags,
+ Map<String, String> labels,
+ Long created,
+ Long size
+) {}
\ No newline at end of file
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerCompose.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerCompose.java
index 1a13fd69..85f6e9ab 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerCompose.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerCompose.java
@@ -17,9 +17,12 @@
package org.apache.camel.karavan.model;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
import java.util.HashMap;
import java.util.Map;
+@JsonIgnoreProperties(ignoreUnknown = true)
public class DockerCompose {
private String version;
private Map<String, DockerComposeService> services;
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerComposeService.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerComposeService.java
index d1b52b01..b1e1f3a5 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerComposeService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerComposeService.java
@@ -17,21 +17,24 @@
package org.apache.camel.karavan.model;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
+/**
+ * A service of the Compose Specification. Compose keys that Karavan does not model, among them
+ * the legacy top-level resource keys replaced by {@code deploy.resources}, are ignored.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
public class DockerComposeService {
private String container_name;
private String image;
private String restart;
- private String cpus;
- private String cpu_percent;
- private String mem_limit;
- private String mem_reservation;
private String command;
private List<String> ports = new ArrayList<>();
private List<DockerVolumeDefinition> volumes = new ArrayList<>();
@@ -40,6 +43,7 @@ public class DockerComposeService {
private List<String> networks = new ArrayList<>();
private Map<String,String> environment = new HashMap<>();
private DockerHealthCheckDefinition healthcheck;
+ private DockerDeployDefinition deploy;
private Map<String,String> labels = new HashMap<>();
public DockerComposeService() {
@@ -142,36 +146,12 @@ public class DockerComposeService {
this.networks = networks;
}
- public String getCpu_percent() {
- return cpu_percent;
- }
-
- public void setCpu_percent(String cpu_percent) {
- this.cpu_percent = cpu_percent;
- }
-
- public String getCpus() {
- return cpus;
- }
-
- public void setCpus(String cpus) {
- this.cpus = cpus;
- }
-
- public String getMem_limit() {
- return mem_limit;
- }
-
- public void setMem_limit(String mem_limit) {
- this.mem_limit = mem_limit;
- }
-
- public String getMem_reservation() {
- return mem_reservation;
+ public DockerDeployDefinition getDeploy() {
+ return deploy;
}
- public void setMem_reservation(String mem_reservation) {
- this.mem_reservation = mem_reservation;
+ public void setDeploy(DockerDeployDefinition deploy) {
+ this.deploy = deploy;
}
public List<DockerVolumeDefinition> getVolumes() {
@@ -204,10 +184,7 @@ public class DockerComposeService {
"container_name='" + container_name + '\'' +
", image='" + image + '\'' +
", restart='" + restart + '\'' +
- ", cpus='" + cpus + '\'' +
- ", cpu_percent='" + cpu_percent + '\'' +
- ", mem_limit='" + mem_limit + '\'' +
- ", mem_reservation='" + mem_reservation + '\'' +
+ ", deploy=" + deploy +
", ports=" + ports +
", networks=" + networks +
", expose=" + expose +
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/ContainerImage.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerDeployDefinition.java
similarity index 50%
copy from karavan-app/src/main/java/org/apache/camel/karavan/model/ContainerImage.java
copy to karavan-app/src/main/java/org/apache/camel/karavan/model/DockerDeployDefinition.java
index 25966f40..00c5538f 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/model/ContainerImage.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerDeployDefinition.java
@@ -17,52 +17,36 @@
package org.apache.camel.karavan.model;
-public class ContainerImage {
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
- private String id;
- private String tag;
- private Long created;
- private Long size;
-
- public ContainerImage() {
- }
-
- public ContainerImage(String id, String tag, Long created, Long size) {
- this.id = id;
- this.tag = tag;
- this.created = created;
- this.size = size;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
+/**
+ * {@code deploy} of the Compose Specification. Only the parts that a standalone Docker
+ * Daemon can enforce are modelled, the remaining Swarm-only keys are ignored.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class DockerDeployDefinition {
- public String getTag() {
- return tag;
- }
+ private DockerResourcesDefinition resources;
- public void setTag(String tag) {
- this.tag = tag;
+ public DockerDeployDefinition() {
}
- public Long getCreated() {
- return created;
+ public DockerDeployDefinition(DockerResourcesDefinition resources) {
+ this.resources = resources;
}
- public void setCreated(Long created) {
- this.created = created;
+ public DockerResourcesDefinition getResources() {
+ return resources;
}
- public Long getSize() {
- return size;
+ public void setResources(DockerResourcesDefinition resources) {
+ this.resources = resources;
}
- public void setSize(Long size) {
- this.size = size;
+ @Override
+ public String toString() {
+ return "DockerDeployDefinition {" +
+ "resources=" + resources +
+ '}';
}
-}
\ No newline at end of file
+}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourceLimits.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourceLimits.java
new file mode 100644
index 00000000..c6091837
--- /dev/null
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourceLimits.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.camel.karavan.model;
+
+/**
+ * CPU and memory limits/reservations of a container, flattened out of
+ * {@code deploy.resources} of the Compose Specification. Values are kept as the raw
+ * Compose strings ("1.5", "512m", ...) and converted to the units the Docker Daemon
+ * expects when the HostConfig is built.
+ */
+public record DockerResourceLimits(String cpuLimit, String memLimit, String pidsLimit,
+ String cpuReservation, String memReservation) {
+
+ public static final DockerResourceLimits NONE = new DockerResourceLimits(null, null, null, null, null);
+
+ public static DockerResourceLimits from(DockerComposeService compose) {
+ var resources = compose != null && compose.getDeploy() != null ? compose.getDeploy().getResources() : null;
+ if (resources == null) {
+ return NONE;
+ }
+ var limits = resources.getLimits();
+ var reservations = resources.getReservations();
+ return new DockerResourceLimits(
+ limits != null ? limits.getCpus() : null,
+ limits != null ? limits.getMemory() : null,
+ limits != null ? limits.getPids() : null,
+ reservations != null ? reservations.getCpus() : null,
+ reservations != null ? reservations.getMemory() : null);
+ }
+}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourceSpecDefinition.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourceSpecDefinition.java
new file mode 100644
index 00000000..77a5c6e7
--- /dev/null
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourceSpecDefinition.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.camel.karavan.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * A single entry of {@code deploy.resources} of the Compose Specification, used both for
+ * {@code limits} and for {@code reservations}. Values are kept as the raw Compose strings
+ * ("1.5", "512m", ...) and converted to the units the Docker Daemon expects when the
+ * HostConfig is built.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class DockerResourceSpecDefinition {
+
+ private String cpus;
+ private String memory;
+ private String pids;
+
+ public DockerResourceSpecDefinition() {
+ }
+
+ public DockerResourceSpecDefinition(String cpus, String memory, String pids) {
+ this.cpus = cpus;
+ this.memory = memory;
+ this.pids = pids;
+ }
+
+ public String getCpus() {
+ return cpus;
+ }
+
+ public void setCpus(String cpus) {
+ this.cpus = cpus;
+ }
+
+ public String getMemory() {
+ return memory;
+ }
+
+ public void setMemory(String memory) {
+ this.memory = memory;
+ }
+
+ public String getPids() {
+ return pids;
+ }
+
+ public void setPids(String pids) {
+ this.pids = pids;
+ }
+
+ @Override
+ public String toString() {
+ return "DockerResourceSpecDefinition {" +
+ "cpus='" + cpus + '\'' +
+ ", memory='" + memory + '\'' +
+ ", pids='" + pids + '\'' +
+ '}';
+ }
+}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourcesDefinition.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourcesDefinition.java
new file mode 100644
index 00000000..e7403f2d
--- /dev/null
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/DockerResourcesDefinition.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.camel.karavan.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+/**
+ * {@code deploy.resources} of the Compose Specification.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class DockerResourcesDefinition {
+
+ private DockerResourceSpecDefinition limits;
+ private DockerResourceSpecDefinition reservations;
+
+ public DockerResourcesDefinition() {
+ }
+
+ public DockerResourcesDefinition(DockerResourceSpecDefinition limits, DockerResourceSpecDefinition reservations) {
+ this.limits = limits;
+ this.reservations = reservations;
+ }
+
+ public DockerResourceSpecDefinition getLimits() {
+ return limits;
+ }
+
+ public void setLimits(DockerResourceSpecDefinition limits) {
+ this.limits = limits;
+ }
+
+ public DockerResourceSpecDefinition getReservations() {
+ return reservations;
+ }
+
+ public void setReservations(DockerResourceSpecDefinition reservations) {
+ this.reservations = reservations;
+ }
+
+ @Override
+ public String toString() {
+ return "DockerResourcesDefinition {" +
+ "limits=" + limits +
+ ", reservations=" + reservations +
+ '}';
+ }
+}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/model/GitConfig.java b/karavan-app/src/main/java/org/apache/camel/karavan/model/GitConfig.java
index a60ac642..ae227044 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/model/GitConfig.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/model/GitConfig.java
@@ -17,58 +17,15 @@
package org.apache.camel.karavan.model;
-public class GitConfig {
- private String uri;
- private String username;
- private String password;
- private String branch;
- private String privateKeyPath;
-
- public GitConfig(String uri, String username, String password, String branch, String privateKeyPath) {
- this.uri = uri;
- this.username = username;
- this.password = password;
- this.branch = branch;
- this.privateKeyPath = privateKeyPath;
- }
-
- public String getUri() {
- return uri;
- }
-
- public void setUri(String uri) {
- this.uri = uri;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- public String getBranch() {
- return branch;
- }
-
- public void setBranch(String branch) {
- this.branch = branch;
- }
-
- public String getPrivateKeyPath() {
- return privateKeyPath;
- }
-
- public void setPrivateKeyPath(String privateKeyPath) {
- this.privateKeyPath = privateKeyPath;
- }
+import java.util.Optional;
+
+public record GitConfig(
+ String repository,
+ Optional<String> username,
+ Optional<String> password,
+ String branch,
+ Optional<Integer> sshPort,
+ Optional<String> privateKeyPath,
+ Optional<String> knownHostsPath,
+ boolean ephemeral) {
}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/CamelComponentService.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/CamelComponentService.java
index ee46af0b..66a66022 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/service/CamelComponentService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/CamelComponentService.java
@@ -4,30 +4,70 @@ import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
-import org.jboss.logging.Logger;
+import org.apache.camel.karavan.util.CamelComponentMetadata;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
+import java.util.*;
@ApplicationScoped
public class CamelComponentService {
- private static final Logger LOGGER = Logger.getLogger(CamelComponentService.class.getName());
-
@Inject
CodeService codeService;
private static JsonArray components;
+ private static List<CamelComponentMetadata> componentsMetadata;
private JsonArray getComponents() {
if (components == null) {
- var json = codeService.getResourceFile("/metadata/components.json");
+ var json = codeService.getResourceFile("/metadata/components-full.json");
components = new JsonArray(json);
}
return components;
}
+ public List<CamelComponentMetadata> getMetadata() {
+ if (componentsMetadata == null) {
+ componentsMetadata = new ArrayList<>();
+ JsonArray jsonComponents = getComponents();
+
+ for (int i = 0; i < jsonComponents.size(); i++) {
+ JsonObject jsonObject = jsonComponents.getJsonObject(i);
+ // Vert.x JsonObject seamlessly maps to Java Records using Jackson under the hood
+ CamelComponentMetadata metadata = jsonObject.mapTo(CamelComponentMetadata.class);
+ componentsMetadata.add(metadata);
+ }
+ }
+ return componentsMetadata;
+ }
+
+ public CamelComponentMetadata getMetadata(String name) {
+ return getMetadata().stream().filter(m -> Objects.equals(name, m.component().name())).findFirst().orElse(null);
+ }
+
+ public List<String> getPropertyNames(String name) {
+ var component = getMetadata(name);
+ if (component != null && component.properties() != null) {
+ return new ArrayList<>(component.properties().keySet());
+ }
+ return List.of();
+ }
+
+ public List<String> getPathPropertyNames(String name) {
+ var component = getMetadata(name);
+ return component.properties().entrySet().stream()
+ .filter(e -> Objects.equals(e.getValue().kind(), "path"))
+ .map(Map.Entry::getKey)
+ .toList();
+ }
+
+ public List<String> getComponentPropertyNames(String name) {
+ var component = getMetadata(name);
+ if (component != null && component.componentProperties() != null) {
+ return new ArrayList<>(component.componentProperties().keySet());
+ }
+ return List.of();
+ }
+
public boolean isComponentRemote(String name) {
try {
var comps = getComponents();
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/CodeService.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/CodeService.java
index bf6495ac..8330fe83 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/service/CodeService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/CodeService.java
@@ -92,7 +92,7 @@ public class CodeService {
KaravanCache karavanCache;
@Inject
- GitService gitService;
+ GitServiceAuth gitServiceAuth;
@Inject
Vertx vertx;
@@ -147,7 +147,7 @@ public class CodeService {
public Map<String, String> getSshFiles() {
Map<String, String> sshFiles = new HashMap<>(2);
- Tuple2<String,String> sshFileNames = gitService.getSShFiles();
+ Tuple2<String,String> sshFileNames = gitServiceAuth.getSShFiles();
if (sshFileNames.getItem1() != null) {
sshFiles.put("id_rsa", getFileString(sshFileNames.getItem1()));
}
@@ -239,7 +239,7 @@ public class CodeService {
public Map<String, String> getBuildInProjectFiles(String projectId) {
Map<String, String> result = new HashMap<>();
- var path = "/" + projectId + (ConfigService.inKubernetes() ? KUBERNETES_FOLDER : DOCKER_FOLDER);
+ var path = getBuildInProjectPath(projectId);
listResources(path).forEach(filename -> {
if (!filename.startsWith(".")) {
@@ -254,8 +254,12 @@ public class CodeService {
}
public List<String> getBuildInProjectFileList(String projectId) {
- var path = "/" + projectId + (ConfigService.inKubernetes() ? KUBERNETES_FOLDER : DOCKER_FOLDER);
- return listResources(path);
+ return listResources(getBuildInProjectPath(projectId));
+ }
+
+ private String getBuildInProjectPath(String projectId) {
+ var runtimeFolder = ConfigService.inKubernetes() ? KUBERNETES_FOLDER : DOCKER_FOLDER;
+ return "/" + projectId + runtimeFolder;
}
public String getResourceFile(String path) {
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/ComplexityService.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/ComplexityService.java
index 0e2d2b7a..dac56666 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/service/ComplexityService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/ComplexityService.java
@@ -38,7 +38,8 @@ public class ComplexityService {
.filter(p -> Objects.equals(p.getType(), ProjectFolder.Type.integration)
|| Objects.equals(p.getType(), ProjectFolder.Type.templates)
|| Objects.equals(p.getType(), ProjectFolder.Type.kamelets)
- || Objects.equals(p.getType(), ProjectFolder.Type.documentation))
+ || Objects.equals(p.getType(), ProjectFolder.Type.documentation)
+ )
.map(this::getProjectComplexity).toList();
}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/GitService.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/GitService.java
index c2d73d0b..c0f22c7e 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/service/GitService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/GitService.java
@@ -16,10 +16,6 @@
*/
package org.apache.camel.karavan.service;
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
-import com.jcraft.jsch.Session;
-import io.smallrye.mutiny.tuples.Tuple2;
import io.smallrye.mutiny.tuples.Tuple3;
import io.vertx.core.Vertx;
import jakarta.enterprise.context.ApplicationScoped;
@@ -34,18 +30,14 @@ import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.api.errors.TransportException;
-import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.lib.*;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.transport.*;
-import org.eclipse.jgit.transport.ssh.jsch.JschConfigSessionFactory;
-import org.eclipse.jgit.transport.ssh.jsch.OpenSshConfig;
+import org.eclipse.jgit.transport.PushResult;
+import org.eclipse.jgit.transport.RemoteRefUpdate;
+import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.treewalk.filter.TreeFilter;
-import org.eclipse.jgit.util.FS;
-import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.jboss.logging.Logger;
import java.io.File;
@@ -55,41 +47,21 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
import java.util.regex.Pattern;
@ApplicationScoped
public class GitService {
- @ConfigProperty(name = "karavan.git.repository")
- String repository;
-
- @ConfigProperty(name = "karavan.git.username")
- Optional<String> username;
-
- @ConfigProperty(name = "karavan.git.password")
- Optional<String> password;
-
- @ConfigProperty(name = "karavan.git.branch", defaultValue = "main")
- String branch;
-
- @ConfigProperty(name = "karavan.git.ssh.port", defaultValue = "22")
- Optional<Integer> sshPort;
-
- @ConfigProperty(name = "karavan.private-key-path")
- Optional<String> privateKeyPath;
-
- @ConfigProperty(name = "karavan.known-hosts-path")
- Optional<String> knownHostsPath;
-
- @ConfigProperty(name = "karavan.git.ephemeral", defaultValue = "false")
- boolean ephemeral;
+ @Inject
+ GitServiceAuth gitServiceAuth;
@Inject
Vertx vertx;
- SshSessionFactory sshSessionFactory;
-
private Git gitForImport;
private static final Logger LOGGER = Logger.getLogger(GitService.class.getName());
@@ -105,57 +77,29 @@ public class GitService {
return gitForImport;
}
- public GitConfig getGitConfig() {
- if (ephemeral) {
- repository = "http://karavan.git";
- username = Optional.of("karavan");
- password = Optional.of("karavan");
- privateKeyPath = Optional.empty();
- knownHostsPath = Optional.empty();
- }
- return new GitConfig(repository, username.orElse(null), password.orElse(null), branch, privateKeyPath.orElse(null));
- }
-
- public Tuple2<String,String> getSShFiles() {
- return Tuple2.of(privateKeyPath.orElse(null), knownHostsPath.orElse(null));
- }
-
- public GitConfig getGitConfigForBuilder() {
- return new GitConfig(repository, username.orElse(null), password.orElse(null), branch, privateKeyPath.orElse(null));
- }
-
public Tuple3<RevCommit, List<RemoteRefUpdate.Status>, List<String>> commitAndPushProject(ProjectFolder projectFolder, List<ProjectFile> files, String message, String authorName, String authorEmail, List<String> fileNames) throws GitAPIException, IOException, URISyntaxException {
LOGGER.info("Commit and push project " + projectFolder.getProjectId());
- GitConfig gitConfig = getGitConfig();
+ GitConfig gitConfig = gitServiceAuth.getGitConfig();
String uuid = UUID.randomUUID().toString();
String folder = vertx.fileSystem().createTempDirectoryBlocking(uuid);
LOGGER.info("Temp folder created " + folder);
Git git = getGit(true, folder);
-// try {
-// git = clone(folder, gitConfig.getUri(), gitConfig.getBranch());
-// checkout(git, false, null, null, gitConfig.getBranch());
-// } catch (RefNotFoundException | InvalidRemoteException | TransportException e) {
-// LOGGER.error("New repository");
-// git = init(folder, gitConfig.getUri(), gitConfig.getBranch());
-// } catch (Exception e) {
-// LOGGER.error("Error", e);
-// }
writeProjectToFolder(folder, projectFolder, files);
addDeletedFilesToIndex(git, folder, projectFolder, files);
- return commitAddedAndPush(git, gitConfig.getBranch(), message, authorName, authorEmail, fileNames, projectFolder.getProjectId());
+ return commitAddedAndPush(git, gitConfig.branch(), message, authorName, authorEmail, fileNames, projectFolder.getProjectId());
}
public List<PathCommitDetails> readProjectsToImport() {
Git importGit = getGitForImport();
if (importGit != null) {
- return readProjectsFromRepository(importGit, new String[0]);
+ return readProjectsFromRepository(importGit);
}
return new ArrayList<>(0);
}
public List<PathCommitDetails> readProjectFromRepository(String projectId) throws GitAPIException, IOException, URISyntaxException {
Git git = getGit(true, vertx.fileSystem().createTempDirectoryBlocking(UUID.randomUUID().toString()));
- return readProjectsFromRepository(git, projectId).stream().filter(d -> Objects.equals(d.projectId(), projectId)).toList();
+ return readProjectsFromRepository(git).stream().filter(d -> Objects.equals(d.projectId(), projectId)).toList();
}
public List<PathCommitDetails> readAllProjectsFromRepository() throws GitAPIException, IOException, URISyntaxException {
@@ -219,7 +163,7 @@ public class GitService {
return pathCommitDetails;
}
- private List<PathCommitDetails> readProjectsFromRepository(Git git, String... filter) {
+ private List<PathCommitDetails> readProjectsFromRepository(Git git) {
LOGGER.info("Read projects...");
List<PathCommitDetails> result = new ArrayList<>();
try {
@@ -234,26 +178,26 @@ public class GitService {
}
public Git getGit(boolean checkout, String folder) throws GitAPIException, IOException, URISyntaxException {
- GitConfig gitConfig = getGitConfig();
- LOGGER.info("Git checkout " + gitConfig.getUri());
+ GitConfig gitConfig = gitServiceAuth.getGitConfig();
+ LOGGER.info("Git checkout " + gitConfig.repository());
LOGGER.info("Temp folder created " + folder);
Git git = null;
- if (ephemeral) {
+ if (gitServiceAuth.isEphemeral()) {
LOGGER.warn("New ephemeral repository");
- git = init(folder, gitConfig.getUri(), gitConfig.getBranch());
+ git = init(folder, gitConfig.repository(), gitConfig.branch());
} else {
try {
- git = clone(folder, gitConfig.getUri(), gitConfig.getBranch());
- var branch = git.branchList().call().stream().filter(ref -> ref.getName().equals("refs/heads/" + gitConfig.getBranch())).findFirst();
+ git = clone(folder, gitConfig.repository(), gitConfig.branch());
+ var branch = git.branchList().call().stream().filter(ref -> ref.getName().equals("refs/heads/" + gitConfig.branch())).findFirst();
if (branch.isEmpty()) {
- createBranch(git, gitConfig.getBranch());
+ createBranch(git, gitConfig.branch());
}
if (checkout) {
- checkout(git, false, null, null, gitConfig.getBranch());
+ checkout(git, false, null, null, gitConfig.branch());
}
} catch (RefNotFoundException | InvalidRemoteException | TransportException e) {
LOGGER.error("New repository", e);
- git = init(folder, gitConfig.getUri(), gitConfig.getBranch());
+ git = init(folder, gitConfig.repository(), gitConfig.branch());
} catch (Exception e) {
LOGGER.error("Error", e);
}
@@ -261,42 +205,6 @@ public class GitService {
return git;
}
- private List<String> readProjectsFromFolder(String folder, String... filter) {
- LOGGER.info("Importing folder " + folder);
- List<String> files = new ArrayList<>();
- vertx.fileSystem().readDirBlocking(folder).forEach(path -> {
- String[] filenames = path.split(Pattern.quote(File.separator));
- String folderName = filenames[filenames.length - 1];
- if (folderName.startsWith(".")) {
- // skip hidden
- } else if (Files.isDirectory(Paths.get(path))) {
- if (filter == null || filter.length == 0 || Arrays.asList(filter).contains(folderName)) {
- LOGGER.info("Reading project from sub-folder " + folderName);
- files.add(folderName);
- }
- }
- });
- return files;
- }
-
- private Map<String, String> readProjectFilesFromFolder(String repoFolder, String projectFolder) {
- LOGGER.infof("Reading files from %s/%s", repoFolder, projectFolder);
- Map<String, String> files = new HashMap<>();
- vertx.fileSystem().readDirBlocking(repoFolder + File.separator + projectFolder).forEach(f -> {
- String[] filenames = f.split(Pattern.quote(File.separator));
- String filename = filenames[filenames.length - 1];
- Path path = Paths.get(f);
- if (!filename.startsWith(".") && !Files.isDirectory(path)) {
- LOGGER.info("Reading " + filename);
- try {
- files.put(filename, Files.readString(path));
- } catch (IOException e) {
- LOGGER.error("Error during file read", e);
- }
- }
- });
- return files;
- }
private void writeProjectToFolder(String folder, ProjectFolder projectFolder, List<ProjectFile> files) throws IOException {
Path projectDir = PathUtils.resolveInside(Paths.get(folder), projectFolder.getProjectId());
@@ -345,11 +253,11 @@ public class GitService {
List<String> messages = new ArrayList<>();
List<RemoteRefUpdate.Status> statuses = new ArrayList<>();
LOGGER.info("Git commit: " + commit);
- if (!ephemeral) {
- PushCommand pushCommand = git.push();
- pushCommand.add(branch).setRemote("origin");
- setCredentials(pushCommand);
- Iterable<PushResult> results = pushCommand.call();
+ if (!gitServiceAuth.isEphemeral()) {
+ PushCommand command = git.push();
+ command.add(branch).setRemote("origin");
+ command = gitServiceAuth.setCredentials(command);
+ Iterable<PushResult> results = command.call();
for (PushResult pr : results) {
if (pr != null) {
LOGGER.info("Git push result: " + pr.getMessages());
@@ -385,7 +293,7 @@ public class GitService {
public void deleteProject(String projectId, String authorName, String authorEmail) {
LOGGER.info("Delete and push project " + projectId);
- GitConfig gitConfig = getGitConfig();
+ GitConfig gitConfig = gitServiceAuth.getGitConfig();
String uuid = UUID.randomUUID().toString();
String folder = vertx.fileSystem().createTempDirectoryBlocking(uuid);
String commitMessage = "Project " + projectId + " is deleted";
@@ -393,9 +301,9 @@ public class GitService {
try {
Git git = getGit(true, folder);
addDeletedFolderToIndex(git, projectId);
- commitAddedAndPush(git, gitConfig.getBranch(), commitMessage, authorName, authorEmail, List.of("."), projectId);
+ commitAddedAndPush(git, gitConfig.branch(), commitMessage, authorName, authorEmail, List.of("."), projectId);
LOGGER.info("Delete Temp folder " + folder);
- vertx.fileSystem().deleteRecursiveBlocking(folder, true);
+ vertx.fileSystem().deleteRecursiveBlocking(folder);
LOGGER.infof("Project %s deleted from Git", projectId);
} catch (RefNotFoundException e) {
LOGGER.error("Repository not found");
@@ -411,7 +319,7 @@ public class GitService {
command.setDirectory(Paths.get(dir).toFile());
command.setURI(uri);
command.setBranch(branch);
- setCredentials(command);
+ command = gitServiceAuth.setCredentials(command);
Git git = command.call();
addRemote(git, uri);
return git;
@@ -425,20 +333,6 @@ public class GitService {
remoteAddCommand.call();
}
- private void fetch(Git git) throws GitAPIException {
- // fetch:
- FetchCommand command = git.fetch();
- setCredentials(command);
- FetchResult result = command.call();
- }
-
- private void pull(Git git) throws GitAPIException {
- // pull:
- PullCommand command = git.pull();
- setCredentials(command);
- PullResult result = command.call();
- }
-
private void createBranch(Git git, String branch) throws GitAPIException {
git.commit().setMessage("Initial commit").call();
git.branchCreate().setName(branch).call();
@@ -458,53 +352,15 @@ public class GitService {
checkoutCommand.call();
}
- private Tuple2<String, Integer> lastCommit(Git git, String path) throws GitAPIException {
- Iterable<RevCommit> log = git.log().addPath(path).setMaxCount(1).call();
- for (RevCommit commit : log) {
- return Tuple2.of(commit.getId().getName(), commit.getCommitTime());
- }
- return null;
- }
-
- public Set<String> getChangedProjects(RevCommit commit) {
- Set<String> files = new HashSet<>();
- Git git = getGitForImport();
- if (git != null) {
- TreeWalk walk = new TreeWalk(git.getRepository());
- walk.setRecursive(true);
- walk.setFilter(TreeFilter.ANY_DIFF);
-
- ObjectId a = commit.getTree().getId();
- RevCommit parent = commit.getParent(0);
- ObjectId b = parent.getTree().getId();
- try {
- walk.reset(b, a);
- List<DiffEntry> changes = DiffEntry.scan(walk);
- changes.stream().forEach(de -> {
- String path = de.getNewPath();
- if (path != null) {
- String[] parts = path.split(Pattern.quote(File.separator));
- if (parts.length > 0) {
- files.add(parts[0]);
- }
- }
- });
- } catch (IOException e) {
- LOGGER.error("Error", e);
- }
- }
- return files;
- }
-
public boolean checkGit() throws Exception {
LOGGER.info("Check git");
- if (ephemeral) {
+ if (gitServiceAuth.isEphemeral()) {
return true;
}
- GitConfig gitConfig = getGitConfig();
+ GitConfig gitConfig = gitServiceAuth.getGitConfig();
String uuid = UUID.randomUUID().toString();
String folder = vertx.fileSystem().createTempDirectoryBlocking(uuid);
- try (Git git = clone(folder, gitConfig.getUri(), gitConfig.getBranch())) {
+ try (Git git = clone(folder, gitConfig.repository(), gitConfig.branch())) {
LOGGER.info("Git is ready");
} catch (Exception e) {
LOGGER.info("Error connecting git: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
@@ -512,41 +368,65 @@ public class GitService {
return true;
}
- private <T extends TransportCommand> T setCredentials(T command) {
- if (privateKeyPath.isPresent() && (repository.startsWith("git") || repository.startsWith("ssh://"))) {
- LOGGER.info("Set SshTransport");
- command.setTransportConfigCallback(transport -> {
- SshTransport sshTransport = (SshTransport) transport;
- sshTransport.setSshSessionFactory(getSshSessionFactory());
- });
- } else if (username.isPresent() && password.isPresent()) {
- LOGGER.info("Set UsernamePasswordCredentialsProvider");
- command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username.get(), password.get()));
- }
- return command;
- }
+ public List<PathCommitDetails> getStateForCommit(String projectId, String commitId) {
+ List<PathCommitDetails> result = new ArrayList<>();
+ try {
+ // Obtain the Git instance (reusing the import cache for read operations)
+ Git git = getGitForImport();
+ if (git == null) {
+ return result;
+ }
- private SshSessionFactory getSshSessionFactory() {
- if (sshSessionFactory == null) {
- sshSessionFactory = new JschConfigSessionFactory() {
- protected void configureJSch(JSch jsch) {
- try {
- jsch.addIdentity(privateKeyPath.get());
- jsch.setKnownHosts(knownHostsPath.get());
- } catch (JSchException e) {
- LOGGER.info("Error configureJSch: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
- }
- }
+ Repository repository = git.getRepository();
+ // Resolve the specific commit ID
+ ObjectId commitObjectId = repository.resolve(commitId);
+ if (commitObjectId == null) {
+ LOGGER.warn("Commit " + commitId + " not found.");
+ return result;
+ }
+
+ try (RevWalk revWalk = new RevWalk(repository)) {
+ RevCommit commit = revWalk.parseCommit(commitObjectId);
+ RevTree tree = commit.getTree();
+
+ // JGit stores commit time in seconds, convert to milliseconds[cite: 1]
+ Long commitTime = Integer.valueOf(commit.getCommitTime()).longValue() * 1000;
+
+ try (TreeWalk treeWalk = new TreeWalk(repository)) {
+ treeWalk.addTree(tree);
+ treeWalk.setRecursive(true); // Traverse into folders automatically
+
+ // Filter the tree walk to only look at the specific project folder
+ treeWalk.setFilter(org.eclipse.jgit.treewalk.filter.PathFilter.create(projectId));
+
+ while (treeWalk.next()) {
+ String path = treeWalk.getPathString();
- @Override
- protected Session createSession(OpenSshConfig.Host hc, String user, String host, int port, FS fs) throws JSchException {
- if (sshPort.isPresent()) {
- port = sshPort.get();
+ // JGit paths typically use '/' internally, but we match the existing separator logic[cite: 1]
+ String[] parts = path.split(Pattern.quote(File.separator));
+ // Fallback in case JGit is enforcing '/' on Windows while File.separator is '\'
+ if (parts.length == 1 && path.contains("/")) {
+ parts = path.split("/");
+ }
+
+ // Ensure we are only grabbing flat files exactly inside the projectId folder
+ if (parts.length == 2 && parts[0].equals(projectId)) {
+ String fileName = parts[1];
+
+ // Load the file content for this specific commit[cite: 1]
+ ObjectId blobId = treeWalk.getObjectId(0);
+ ObjectLoader loader = repository.open(blobId);
+ String content = new String(loader.getBytes(), StandardCharsets.UTF_8);
+
+ // Create the PathCommitDetails record (isFolder = false for files)[cite: 3]
+ result.add(new PathCommitDetails(projectId, fileName, commitId, commitTime, content, false));
+ }
}
- return super.createSession(hc, user, host, port, fs);
}
- };
+ }
+ } catch (Exception e) {
+ LOGGER.error("Error retrieving state for commit " + commitId, e);
}
- return sshSessionFactory;
+ return result;
}
}
\ No newline at end of file
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/GitServiceAuth.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/GitServiceAuth.java
new file mode 100644
index 00000000..a6ab3584
--- /dev/null
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/GitServiceAuth.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.karavan.service;
+
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
+import io.smallrye.mutiny.tuples.Tuple2;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.apache.camel.karavan.kubernetes.KubernetesService;
+import org.apache.camel.karavan.model.GitConfig;
+import org.eclipse.jgit.api.TransportCommand;
+import org.eclipse.jgit.transport.SshSessionFactory;
+import org.eclipse.jgit.transport.SshTransport;
+import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
+import org.eclipse.jgit.transport.ssh.jsch.JschConfigSessionFactory;
+import org.eclipse.jgit.transport.ssh.jsch.OpenSshConfig;
+import org.eclipse.jgit.util.FS;
+import org.jboss.logging.Logger;
+
+import java.util.Optional;
+
+@ApplicationScoped
+public class GitServiceAuth {
+
+ @Inject
+ KubernetesService kubernetesService;
+
+ private static final Logger LOGGER = Logger.getLogger(GitServiceAuth.class.getName());
+
+ public GitConfig getGitConfig() {
+ String repository;
+ Optional<String> username;
+ Optional<String> password;
+ String branch;
+ Optional<Integer> sshPort;
+ Optional<String> privateKeyPath;
+ Optional<String> knownHostsPath;
+ boolean ephemeral = false;
+
+ if (ConfigService.inDocker()) {
+ repository = org.eclipse.microprofile.config.ConfigProvider.getConfig().getValue("karavan.git.repository", String.class);
+ username = org.eclipse.microprofile.config.ConfigProvider.getConfig().getOptionalValue("karavan.git.username", String.class);
+ password = org.eclipse.microprofile.config.ConfigProvider.getConfig().getOptionalValue("karavan.git.password", String.class);
+ branch = org.eclipse.microprofile.config.ConfigProvider.getConfig().getValue("karavan.git.branch", String.class);
+ sshPort = org.eclipse.microprofile.config.ConfigProvider.getConfig().getOptionalValue("karavan.git.ssh.port", Integer.class);
+ privateKeyPath = org.eclipse.microprofile.config.ConfigProvider.getConfig().getOptionalValue("karavan.private-key-path", String.class);
+ knownHostsPath = org.eclipse.microprofile.config.ConfigProvider.getConfig().getOptionalValue("karavan.known-hosts-path", String.class);
+ ephemeral = org.eclipse.microprofile.config.ConfigProvider.getConfig().getOptionalValue("karavan.git.ephemeral", Boolean.class).orElse(false);
+ } else {
+ repository = kubernetesService.getKaravanSecret("karavan.git.repository");
+ username = Optional.ofNullable(kubernetesService.getKaravanSecret("karavan.git.username"));
+ password = Optional.ofNullable(kubernetesService.getKaravanSecret("karavan.git.password"));
+ branch = kubernetesService.getKaravanSecret("karavan.git.branch");
+ sshPort = Optional.ofNullable(kubernetesService.getKaravanSecret("karavan.git.ssh.port")).map(Integer::parseInt);
+ privateKeyPath = Optional.ofNullable(kubernetesService.getKaravanSecret("karavan.private-key-path"));
+ knownHostsPath = Optional.ofNullable(kubernetesService.getKaravanSecret("karavan.known-hosts-path"));
+ var ephemeralValue = kubernetesService.getKaravanSecret("karavan.git.ephemeral");
+ ephemeral = Boolean.parseBoolean(ephemeralValue);
+ }
+
+ if (ephemeral) {
+ repository = "http://karavan.git";
+ username = Optional.of("karavan");
+ password = Optional.of("karavan");
+ privateKeyPath = Optional.empty();
+ knownHostsPath = Optional.empty();
+ return new GitConfig(repository, username, password, branch, sshPort, privateKeyPath, knownHostsPath, ephemeral);
+ } else {
+ return new GitConfig(repository, username, password, branch, sshPort, privateKeyPath, knownHostsPath, ephemeral);
+ }
+
+ }
+
+ public Tuple2<String,String> getSShFiles() {
+ return Tuple2.of(getGitConfig().privateKeyPath().orElse(null), getGitConfig().knownHostsPath().orElse(null));
+ }
+
+ public <T extends TransportCommand> T setCredentials(T command) {
+ var gitConfig = getGitConfig();
+ if (gitConfig.privateKeyPath().isPresent() && (gitConfig.repository().startsWith("git") || gitConfig.repository().startsWith("ssh://"))) {
+ LOGGER.info("Set SshTransport");
+ command.setTransportConfigCallback(transport -> {
+ SshTransport sshTransport = (SshTransport) transport;
+ sshTransport.setSshSessionFactory(getSshSessionFactory());
+ });
+ } else if (gitConfig.username().isPresent() && gitConfig.password().isPresent()) {
+ LOGGER.info("Set UsernamePasswordCredentialsProvider");
+ command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitConfig.username().get(), gitConfig.password().get()));
+ }
+ return command;
+ }
+
+ public SshSessionFactory getSshSessionFactory() {
+ var gitConfig = getGitConfig();
+ return new JschConfigSessionFactory() {
+ protected void configureJSch(JSch jsch) {
+ try {
+ jsch.addIdentity(gitConfig.privateKeyPath().get());
+ jsch.setKnownHosts(gitConfig.knownHostsPath().get());
+ } catch (JSchException e) {
+ LOGGER.info("Error configureJSch: " + (e.getCause() != null ? e.getCause().getMessage() : e.getMessage()));
+ }
+ }
+
+ @Override
+ protected Session createSession(OpenSshConfig.Host hc, String user, String host, int port, FS fs) throws JSchException {
+ if (gitConfig.sshPort().isPresent()) {
+ port = gitConfig.sshPort().get();
+ }
+ return super.createSession(hc, user, host, port, fs);
+ }
+ };
+ }
+
+ public boolean isEphemeral() {
+ return getGitConfig().ephemeral();
+ }
+}
\ No newline at end of file
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/ProjectService.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/ProjectService.java
index 49aeeb7d..8f3ba700 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/service/ProjectService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/ProjectService.java
@@ -62,10 +62,10 @@ public class ProjectService {
GitService gitService;
@Inject
- CodeService codeService;
+ GitServiceAuth gitServiceAuth;
@Inject
- ConfigService configService;
+ CodeService codeService;
@Inject
KubernetesService kubernetesService;
@@ -148,9 +148,7 @@ public class ProjectService {
}
public void buildProject(ProjectFolder projectFolder, String tag) throws Exception {
- tag = tag != null && !tag.isBlank()
- ? tag
- : Instant.now().toString().substring(0, 19).replace(":", "-");
+ tag = tag != null && !tag.isBlank() ? tag : Instant.now().toString().substring(0, 19).replace(":", "-");
var name = projectFolder.getProjectId() + "-builder";
var session = authService.createAndSaveSession(name, false, true);
if (ConfigService.inKubernetes()) {
@@ -159,12 +157,11 @@ public class ProjectService {
kubernetesService.runBuildProject(projectFolder.getProjectId(), podFragment, Map.of(ENV_VAR_BUILDER_SESSION_ID, session.getSessionId()));
} else {
Map<String, String> sshFiles = codeService.getSshFiles();
- String script = codeService.getBuilderScript();
String composeFragment = codeService.getBuilderComposeFragment(projectFolder.getProjectId(), tag);
DockerComposeService compose = DockerComposeConverter.fromCode(composeFragment, name);
compose.addEnvironment(ENV_VAR_RUN_IN_BUILD_MODE, "true");
compose.addEnvironment(ENV_VAR_BUILDER_SESSION_ID, session.getSessionId());
- dockerForKaravan.runBuildProject(projectFolder, script, compose, sshFiles, tag);
+ dockerForKaravan.runBuildProject(projectFolder, compose, sshFiles, tag);
}
}
@@ -386,17 +383,50 @@ public class ProjectService {
}
public void importProjects(boolean onlyNew) {
- LOGGER.info("Import " +(onlyNew ? "Only New" : "")+ " projects from git: " + gitService.getGitConfig().getUri());
+ boolean isDev = "dev".equalsIgnoreCase(environment);
+ boolean effectiveOnlyNew = isDev ? onlyNew : false;
+ LOGGER.info("Import " + (effectiveOnlyNew ? "Only New" : "All") + " projects from git: " + gitServiceAuth.getGitConfig().repository());
try {
- List<PathCommitDetails> pathCommitDetails = onlyNew ? gitService.readAllProjectsFromRepository() : gitService.readProjectsToImport();
+ List<PathCommitDetails> pathCommitDetails = effectiveOnlyNew ? gitService.readAllProjectsFromRepository() : gitService.readProjectsToImport();
List<PathCommitDetails> projectPaths = pathCommitDetails.stream().filter(PathCommitDetails::isFolder).toList();
+ List<String> gitProjectIds = projectPaths.stream().map(PathCommitDetails::projectId).toList();
+
+ // In test/prod, remove projects from cache that are not in Git (if no active deployment/container)
+ if (!isDev) {
+ List<ProjectFolder> cachedProjects = karavanCache.getFolders(); // Adjust getter based on your Cache definition
+ cachedProjects.forEach(cachedProject -> {
+ String projectId = cachedProject.getProjectId();
+ boolean isBuiltIn = ProjectFolder.getBuildInNames().contains(projectId);
+ if (!isBuiltIn && !gitProjectIds.contains(projectId)) {
+ if (!isProjectInUse(projectId)) {
+ LOGGER.info("Removing stale project " + projectId + " from cache (not in Git and not deployed)");
+ karavanCache.deleteProject(projectId);
+ } else {
+ LOGGER.info("Skipping removal of project " + projectId + " (not in git) because it has an active deployment/container.");
+ }
+ }
+ });
+ }
+
projectPaths.forEach(folderDetails -> {
ProjectFolder projectFolder;
ProjectFolderCommited projectFolderCommited;
String folderName = folderDetails.projectId();
var folderFiles = pathCommitDetails.stream().filter(d -> !d.isFolder() && Objects.equals(d.projectId(), folderName)).toList();
- boolean needImport = !onlyNew || karavanCache.getProject(folderName) == null;
+ boolean isBuiltIn = ProjectFolder.getBuildInNames().contains(folderName);
+
+ // In test/prod, add only projects that contain the respective {environment}.kubernetes.yaml
+ if (!isDev && !isBuiltIn) {
+ boolean hasEnvDeploymentFile = hadEnvironmentSpecificDeploymentFile(folderFiles.stream().map(PathCommitDetails::fileName).collect(Collectors.toList()));
+
+ if (!hasEnvDeploymentFile) {
+ LOGGER.info("Project " + folderName + " skipped! (Missing " + environment + " deployment resource)");
+ return; // Skip importing this project
+ }
+ }
+
+ boolean needImport = !effectiveOnlyNew || karavanCache.getProject(folderName) == null;
LOGGER.info("Project " + folderName + " " + (needImport ? "is loading!" : "skipped!"));
if (needImport) {
@@ -415,13 +445,14 @@ public class ProjectService {
projectFolderCommited = new ProjectFolderCommited(projectFolder.getProjectId(), folderDetails.commitId(), folderDetails.commitTime());
karavanCache.saveProjectCommited(projectFolderCommited);
-
folderFiles.forEach(fileDetails -> {
var file = new ProjectFile(fileDetails.fileName(), fileDetails.content(), folderName, fileDetails.commitTime());
var commitedFile = ProjectFileCommited.fromFile(file, fileDetails.commitId());
karavanCache.saveProjectFileCommited(commitedFile);
var fileInCache = karavanCache.getProjectFile(file.getProjectId(), file.getName());
- if (fileInCache == null || fileInCache.getLastUpdate() < file.getLastUpdate()) {
+
+ // Enforce overwrites: Always rewrite files in test/prod environments (bypass timestamp checks)
+ if (fileInCache == null || !isDev || fileInCache.getLastUpdate() < file.getLastUpdate()) {
karavanCache.saveProjectFile(file, null, false);
}
});
@@ -431,4 +462,34 @@ public class ProjectService {
LOGGER.error("Error during project import", e);
}
}
+
+ private boolean hadEnvironmentSpecificDeploymentFile(List<String> fileNames) {
+ if (ConfigService.inDocker()) {
+ return fileNames.stream().anyMatch(name -> name.equals(environment + "." + DOCKER_COMPOSE_FILENAME));
+ } else {
+ return fileNames.stream().anyMatch(name -> name.equals(environment + "." + KUBERNETES_YAML_FILENAME));
+ }
+
+ }
+
+ private boolean isProjectInUse(String projectId) {
+ var pods = karavanCache.getPodContainerStatusesByProject(projectId);
+ return !pods.isEmpty();
+ }
+
+ public void revertProjectToCommit(String projectId, String commitId) {
+ var filesInGit = gitService.getStateForCommit(projectId, commitId);
+
+ // remove files from cache
+ var fileNames = karavanCache.getProjectFiles(projectId).stream().map(ProjectFile::getName).toList();
+ for (var cachedFileName : fileNames) {
+ karavanCache.deleteProjectFile(projectId, cachedFileName);
+ }
+
+ // add files from git
+ for (var file : filesInGit) {
+ var projectFile = new ProjectFile(file.fileName(), file.content(), projectId, file.commitTime());
+ karavanCache.saveProjectFile(projectFile, null, true);
+ }
+ }
}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/RegistryImageService.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/RegistryImageService.java
new file mode 100644
index 00000000..af14e0ed
--- /dev/null
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/RegistryImageService.java
@@ -0,0 +1,412 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.karavan.service;
+
+import io.vertx.core.json.JsonArray;
+import io.vertx.core.json.JsonObject;
+import io.vertx.core.net.PemTrustOptions;
+import io.vertx.ext.web.client.WebClientOptions;
+import io.vertx.mutiny.core.Vertx;
+import io.vertx.mutiny.core.buffer.Buffer;
+import io.vertx.mutiny.ext.web.client.HttpRequest;
+import io.vertx.mutiny.ext.web.client.HttpResponse;
+import io.vertx.mutiny.ext.web.client.WebClient;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.apache.camel.karavan.KaravanConstants;
+import org.apache.camel.karavan.cache.KaravanCache;
+import org.apache.camel.karavan.kubernetes.KubernetesService;
+import org.apache.camel.karavan.model.ContainerImage;
+import org.apache.camel.karavan.model.RegistryConfig;
+import org.eclipse.microprofile.config.inject.ConfigProperty;
+import org.jboss.logging.Logger;
+
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * Reads container images from an OCI Distribution registry (`/v2/` API), the only API implemented by
+ * every registry we care about: Distribution (`registry:5000`), Harbor, Quay, GHCR, ECR, GAR, ACR,
+ * Nexus, Artifactory and Docker Hub. Lookup is always per project (`{group}/{projectId}`), so
+ * `/v2/_catalog` (unsupported on Hub and ECR) is never used.
+ * <p>
+ * Note: sizes come from the layer/config descriptors and are therefore <b>compressed</b> sizes,
+ * unlike the uncompressed sizes reported by the Docker Engine API.
+ */
+@ApplicationScoped
+public class RegistryImageService {
+
+ private static final Logger LOGGER = Logger.getLogger(RegistryImageService.class.getName());
+
+ private static final String OCI_INDEX = "application/vnd.oci.image.index.v1+json";
+ private static final String DOCKER_MANIFEST_LIST = "application/vnd.docker.distribution.manifest.list.v2+json";
+ private static final String OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
+ private static final String DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
+ private static final String MANIFEST_ACCEPT = String.join(", ", OCI_INDEX, DOCKER_MANIFEST_LIST, OCI_MANIFEST, DOCKER_MANIFEST);
+
+ private static final String DIGEST_HEADER = "Docker-Content-Digest";
+ private static final int TIMEOUT = 10000;
+ // Tokens are refreshed this many seconds before the registry expires them
+ private static final long TOKEN_EXPIRY_MARGIN = 30;
+
+ @ConfigProperty(name = "karavan.environment", defaultValue = KaravanConstants.DEV)
+ String environment;
+
+ @ConfigProperty(name = "karavan.container-image.registry-insecure", defaultValue = "false")
+ boolean insecure;
+
+ @ConfigProperty(name = "karavan.container-image.registry-ca-configmap")
+ Optional<String> caConfigMap;
+
+ @ConfigProperty(name = "karavan.container-image.registry-ca-key", defaultValue = "ca.crt")
+ String caConfigMapKey;
+
+ @Inject
+ Vertx vertx;
+
+ @Inject
+ RegistryService registryService;
+
+ @Inject
+ KubernetesService kubernetesService;
+
+ @Inject
+ KaravanCache karavanCache;
+
+ private WebClient webClient;
+ private volatile String baseUrl;
+ private final Map<String, CachedToken> tokens = new ConcurrentHashMap<>();
+
+ private record CachedToken(String header, long expiresAt) {
+ }
+
+ private record ManifestInfo(String digest, String configDigest, long size) {
+ }
+
+ public synchronized WebClient getWebClient() {
+ if (webClient == null) {
+ WebClientOptions options = new WebClientOptions().setSsl(false).setKeepAlive(true);
+ if (insecure) {
+ options.setTrustAll(true).setVerifyHost(false);
+ }
+ getRegistryCa().ifPresent(ca -> options.setPemTrustOptions(
+ new PemTrustOptions().addCertValue(io.vertx.core.buffer.Buffer.buffer(ca))));
+ webClient = WebClient.create(vertx, options);
+ }
+ return webClient;
+ }
+
+ /**
+ * Images of a project as stored in the registry, one row per manifest digest with all the tags
+ * pointing at it, newest first. Same shape for Docker and Kubernetes.
+ */
+ public List<ContainerImage> getImagesForProject(String projectId) {
+ RegistryConfig config = registryService.getRegistryConfig();
+ String repository = config.getGroup() + "/" + projectId;
+ try {
+ String base = getBaseUrl();
+ if (base == null) {
+ return List.of();
+ }
+ String authorization = getAuthorization(base, config, repository);
+ List<String> tags = getTags(base, repository, authorization);
+ // Tags are shown with the configured registry address, not the address used to call the
+ // API, so that the name can be used as an image name in docker-compose/kubernetes.yaml
+
+ String registry = config.getRegistry();
+ if (Objects.equals(config.getRegistry(), "registry:5000")) {
+ var container = karavanCache.getPodContainerStatus("registry", environment);
+ if (container != null) {
+ var port = container.getPorts().stream().filter(p -> p.getPrivatePort() == 5000).findFirst();
+ if (port.isPresent()) {
+ registry = "localhost:" + port.get().getPublicPort();
+ }
+ }
+ }
+ String imagePrefix = registry + "/" + repository + ":";
+
+ Map<String, List<String>> tagsByDigest = new LinkedHashMap<>();
+ Map<String, ContainerImage> imagesByDigest = new LinkedHashMap<>();
+ for (String tag : tags) {
+ ManifestInfo manifest = getManifest(base, repository, tag, authorization);
+ if (manifest == null) {
+ continue;
+ }
+ tagsByDigest.computeIfAbsent(manifest.digest(), k -> new ArrayList<>()).add(imagePrefix + tag);
+ if (!imagesByDigest.containsKey(manifest.digest())) {
+ imagesByDigest.put(manifest.digest(), getImageConfig(base, repository, manifest, authorization));
+ }
+ }
+ return imagesByDigest.entrySet().stream()
+ .map(e -> new ContainerImage(e.getKey(), tagsByDigest.get(e.getKey()),
+ e.getValue().labels(), e.getValue().created(), e.getValue().size()))
+ .sorted(Comparator.comparing(ContainerImage::created).reversed()
+ .thenComparing(s -> s.tags() != null ? String.join(",", s.tags()) : ""))
+ .toList();
+ } catch (Exception e) {
+ LOGGER.error("Failed to get images for project " + projectId + ": " + getMessage(e));
+ return List.of();
+ }
+ }
+
+ private List<String> getTags(String base, String repository, String authorization) {
+ HttpResponse<Buffer> response = send(base + "/v2/" + repository + "/tags/list", authorization, "application/json");
+ if (response == null || response.statusCode() == 404) {
+ // Repository does not exist yet: the project was never built
+ return List.of();
+ }
+ if (response.statusCode() != 200) {
+ LOGGER.warn("Failed to list tags of " + repository + ": " + response.statusCode() + " " + response.statusMessage());
+ return List.of();
+ }
+ JsonArray tags = response.bodyAsJsonObject().getJsonArray("tags");
+ if (tags == null) {
+ return List.of();
+ }
+ return tags.stream().filter(t -> t instanceof String).map(Object::toString).toList();
+ }
+
+ private ManifestInfo getManifest(String base, String repository, String reference, String authorization) {
+ HttpResponse<Buffer> response = send(base + "/v2/" + repository + "/manifests/" + reference, authorization, MANIFEST_ACCEPT);
+ if (response == null || response.statusCode() != 200) {
+ LOGGER.warn("Failed to get manifest " + repository + ":" + reference
+ + (response != null ? ": " + response.statusCode() + " " + response.statusMessage() : ""));
+ return null;
+ }
+ String digest = response.getHeader(DIGEST_HEADER);
+ JsonObject manifest = response.bodyAsJsonObject();
+ JsonArray children = manifest.getJsonArray("manifests");
+ if (children != null && !children.isEmpty()) {
+ // Index/manifest list: describe the linux/amd64 child, keep the index digest as the id
+ JsonObject child = selectPlatform(children);
+ ManifestInfo childInfo = getManifest(base, repository, child.getString("digest"), authorization);
+ if (childInfo == null) {
+ return null;
+ }
+ return new ManifestInfo(digest != null ? digest : childInfo.digest(), childInfo.configDigest(), childInfo.size());
+ }
+ JsonObject imageConfig = manifest.getJsonObject("config");
+ if (imageConfig == null) {
+ return null;
+ }
+ long size = imageConfig.getLong("size", 0L);
+ JsonArray layers = manifest.getJsonArray("layers");
+ if (layers != null) {
+ for (int i = 0; i < layers.size(); i++) {
+ size += layers.getJsonObject(i).getLong("size", 0L);
+ }
+ }
+ return new ManifestInfo(digest, imageConfig.getString("digest"), size);
+ }
+
+ private JsonObject selectPlatform(JsonArray children) {
+ for (int i = 0; i < children.size(); i++) {
+ JsonObject child = children.getJsonObject(i);
+ JsonObject platform = child.getJsonObject("platform");
+ if (platform != null && "linux".equals(platform.getString("os")) && "amd64".equals(platform.getString("architecture"))) {
+ return child;
+ }
+ }
+ return children.getJsonObject(0);
+ }
+
+ private ContainerImage getImageConfig(String base, String repository, ManifestInfo manifest, String authorization) {
+ Long created = null;
+ Map<String, String> labels = Map.of();
+ if (manifest.configDigest() != null) {
+ HttpResponse<Buffer> response = send(base + "/v2/" + repository + "/blobs/" + manifest.configDigest(), authorization, "application/json");
+ if (response != null && response.statusCode() == 200) {
+ JsonObject config = response.bodyAsJsonObject();
+ created = toEpochSeconds(config.getString("created"));
+ JsonObject imageLabels = config.getJsonObject("config") != null
+ ? config.getJsonObject("config").getJsonObject("Labels")
+ : null;
+ if (imageLabels != null) {
+ labels = new LinkedHashMap<>();
+ for (String key : imageLabels.fieldNames()) {
+ labels.put(key, imageLabels.getString(key));
+ }
+ }
+ } else {
+ LOGGER.warn("Failed to get image config " + repository + "@" + manifest.configDigest());
+ }
+ }
+ return new ContainerImage(manifest.digest(), List.of(), labels, created != null ? created : 0L, manifest.size());
+ }
+
+ private Long toEpochSeconds(String created) {
+ try {
+ return created != null ? Instant.parse(created).getEpochSecond() : null;
+ } catch (Exception e) {
+ LOGGER.warn("Unparseable image creation date: " + created);
+ return null;
+ }
+ }
+
+ private HttpResponse<Buffer> send(String url, String authorization, String accept) {
+ try {
+ HttpRequest<Buffer> request = getWebClient().getAbs(url).putHeader("Accept", accept).timeout(TIMEOUT);
+ if (authorization != null) {
+ request.putHeader("Authorization", authorization);
+ }
+ return request.send().subscribeAsCompletionStage().toCompletableFuture().get();
+ } catch (Exception e) {
+ LOGGER.warn("Registry request failed " + url + ": " + getMessage(e));
+ return null;
+ }
+ }
+
+ /**
+ * Registry base URL, discovered once by pinging `/v2/`. Registries configured without a scheme
+ * are tried over https first, and over http as well when insecure registries are allowed.
+ */
+ private String getBaseUrl() {
+ if (baseUrl != null) {
+ return baseUrl;
+ }
+ String address = registryService.getRegistryAddress();
+ List<String> candidates;
+ if (address.startsWith("http://") || address.startsWith("https://")) {
+ candidates = List.of(address);
+ } else if (address.equals("docker.io") || address.equals("index.docker.io")) {
+ candidates = List.of("https://registry-1.docker.io");
+ } else {
+ candidates = insecure
+ ? List.of("https://" + address, "http://" + address)
+ : List.of("https://" + address);
+ }
+ for (String candidate : candidates) {
+ String base = candidate.endsWith("/") ? candidate.substring(0, candidate.length() - 1) : candidate;
+ // Any HTTP answer (including 401) means we found the registry API
+ if (send(base + "/v2/", null, "application/json") != null) {
+ baseUrl = base;
+ return baseUrl;
+ }
+ }
+ LOGGER.error("Container image registry is not reachable: " + address);
+ return null;
+ }
+
+ /**
+ * Authorization header for a pull on the given repository: a bearer token obtained from the
+ * `WWW-Authenticate` challenge, or plain Basic for registries that use it. Tokens are cached
+ * per scope until they expire.
+ */
+ private String getAuthorization(String base, RegistryConfig config, String repository) {
+ String scope = "repository:" + repository + ":pull";
+ CachedToken cached = tokens.get(scope);
+ if (cached != null && cached.expiresAt() > Instant.now().getEpochSecond()) {
+ return cached.header();
+ }
+ HttpResponse<Buffer> ping = send(base + "/v2/", null, "application/json");
+ if (ping == null) {
+ return null;
+ }
+ if (ping.statusCode() != 401) {
+ // Open registry: send Basic anyway if credentials are configured, some registries
+ // answer 200 on /v2/ but require authentication on private repositories
+ return basicHeader(config);
+ }
+ Map<String, String> challenge = parseChallenge(ping.getHeader("WWW-Authenticate"));
+ String realm = challenge.get("realm");
+ if (realm == null) {
+ return basicHeader(config);
+ }
+ if (!"bearer".equals(challenge.get("scheme"))) {
+ return basicHeader(config);
+ }
+ StringBuilder url = new StringBuilder(realm)
+ .append(realm.contains("?") ? "&" : "?")
+ .append("scope=").append(encode(scope));
+ if (challenge.get("service") != null) {
+ url.append("&service=").append(encode(challenge.get("service")));
+ }
+ HttpResponse<Buffer> response = send(url.toString(), basicHeader(config), "application/json");
+ if (response == null || response.statusCode() != 200) {
+ LOGGER.warn("Failed to get registry token for " + scope
+ + (response != null ? ": " + response.statusCode() + " " + response.statusMessage() : ""));
+ return basicHeader(config);
+ }
+ JsonObject body = response.bodyAsJsonObject();
+ String token = body.getString("token", body.getString("access_token"));
+ if (token == null) {
+ return basicHeader(config);
+ }
+ long expiresIn = body.getLong("expires_in", 300L);
+ String header = "Bearer " + token;
+ tokens.put(scope, new CachedToken(header, Instant.now().getEpochSecond() + Math.max(expiresIn - TOKEN_EXPIRY_MARGIN, 1)));
+ return header;
+ }
+
+ private String basicHeader(RegistryConfig config) {
+ if (config.getUsername() == null || config.getUsername().isBlank()) {
+ return null;
+ }
+ String credentials = config.getUsername() + ":" + (config.getPassword() != null ? config.getPassword() : "");
+ return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
+ }
+
+ /**
+ * Parses `Bearer realm="https://auth.example.org/token",service="registry.example.org"`
+ * into `{scheme: bearer, realm: ..., service: ...}`.
+ */
+ private Map<String, String> parseChallenge(String header) {
+ Map<String, String> result = new LinkedHashMap<>();
+ if (header == null || header.isBlank()) {
+ return result;
+ }
+ String trimmed = header.trim();
+ int space = trimmed.indexOf(' ');
+ if (space < 0) {
+ result.put("scheme", trimmed.toLowerCase());
+ return result;
+ }
+ result.put("scheme", trimmed.substring(0, space).toLowerCase());
+ for (String part : trimmed.substring(space + 1).split(",")) {
+ String[] keyValue = part.split("=", 2);
+ if (keyValue.length == 2) {
+ result.put(keyValue[0].trim().toLowerCase(), keyValue[1].trim().replaceAll("^\"|\"$", ""));
+ }
+ }
+ return result;
+ }
+
+ private Optional<String> getRegistryCa() {
+ if (caConfigMap.isEmpty() || caConfigMap.get().isBlank() || !ConfigService.inKubernetes()) {
+ return Optional.empty();
+ }
+ try {
+ var configMap = kubernetesService.getConfigMap(caConfigMap.get());
+ var data = configMap != null ? configMap.getData() : null;
+ return Optional.ofNullable(data != null ? data.get(caConfigMapKey) : null);
+ } catch (Exception e) {
+ LOGGER.error("Failed to read registry CA from ConfigMap " + caConfigMap.get() + ": " + getMessage(e));
+ return Optional.empty();
+ }
+ }
+
+ private String encode(String value) {
+ return URLEncoder.encode(value, StandardCharsets.UTF_8);
+ }
+
+ private String getMessage(Exception e) {
+ return e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
+ }
+}
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/service/RegistryService.java b/karavan-app/src/main/java/org/apache/camel/karavan/service/RegistryService.java
index b9957d43..45af0852 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/service/RegistryService.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/service/RegistryService.java
@@ -16,6 +16,7 @@
*/
package org.apache.camel.karavan.service;
+import io.vertx.core.json.JsonObject;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.camel.karavan.kubernetes.KubernetesService;
@@ -23,6 +24,9 @@ import org.apache.camel.karavan.model.RegistryConfig;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.jboss.logging.Logger;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.Objects;
import java.util.Optional;
@ApplicationScoped
@@ -53,10 +57,84 @@ public class RegistryService {
imageGroup = i != null ? i : group;
registryUsername = kubernetesService.getKaravanSecret("image-registry-username");
registryPassword = kubernetesService.getKaravanSecret("image-registry-password");
+ if (registryUsername == null || registryUsername.isBlank()) {
+ // Zero-config: reuse the image pull secret of the Talisman pod/ServiceAccount
+ String[] credentials = getCredentialsFromPullSecrets(registryUrl);
+ if (credentials != null) {
+ registryUsername = credentials[0];
+ registryPassword = credentials[1];
+ }
+ }
}
return new RegistryConfig(registryUrl, imageGroup, registryUsername, registryPassword);
}
+ /**
+ * Registry address used to call the registry API. In local dev mode (outside Docker and
+ * Kubernetes) the in-compose registry is reachable on its published port only.
+ */
+ public String getRegistryAddress() {
+ String registryUrl = getRegistryConfig().getRegistry();
+ if (!ConfigService.inKubernetes() && !ConfigService.inDocker() && "registry:5000".equalsIgnoreCase(registryUrl)) {
+ registryUrl = "localhost:5555";
+ }
+ return registryUrl;
+ }
+
+ /**
+ * Resolves `username/password` for the registry host from the `kubernetes.io/dockerconfigjson`
+ * pull secrets available to Talisman, so the registry does not have to be configured twice.
+ */
+ private String[] getCredentialsFromPullSecrets(String registry) {
+ String host = normalizeRegistryHost(registry);
+ for (String dockerConfig : kubernetesService.getDockerConfigJsons()) {
+ try {
+ JsonObject auths = new JsonObject(dockerConfig).getJsonObject("auths");
+ if (auths == null) {
+ continue;
+ }
+ for (String key : auths.fieldNames()) {
+ if (!Objects.equals(normalizeRegistryHost(key), host)) {
+ continue;
+ }
+ JsonObject entry = auths.getJsonObject(key);
+ String username = entry.getString("username");
+ String password = entry.getString("password");
+ if (username == null && entry.getString("auth") != null) {
+ String decoded = new String(Base64.getDecoder().decode(entry.getString("auth")), StandardCharsets.UTF_8);
+ int colon = decoded.indexOf(':');
+ if (colon > 0) {
+ username = decoded.substring(0, colon);
+ password = decoded.substring(colon + 1);
+ }
+ }
+ if (username != null) {
+ return new String[]{username, password};
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.warn("Failed to parse image pull secret: " + e.getMessage());
+ }
+ }
+ return null;
+ }
+
+ private String normalizeRegistryHost(String registry) {
+ if (registry == null) {
+ return null;
+ }
+ String host = registry.replaceFirst("^https?://", "");
+ int slash = host.indexOf('/');
+ if (slash > 0) {
+ host = host.substring(0, slash);
+ }
+ // Docker Hub is referenced by several aliases in docker config files
+ if (host.equals("index.docker.io") || host.equals("registry-1.docker.io") || host.equals("registry.hub.docker.com")) {
+ host = "docker.io";
+ }
+ return host;
+ }
+
public String getRegistryWithGroupForSync() {
String registryUrl = registry;
if (!ConfigService.inKubernetes() && registryUrl.equalsIgnoreCase("registry:5000")) {
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/util/CamelComponentMetadata.java b/karavan-app/src/main/java/org/apache/camel/karavan/util/CamelComponentMetadata.java
new file mode 100644
index 00000000..2846e597
--- /dev/null
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/util/CamelComponentMetadata.java
@@ -0,0 +1,108 @@
+package org.apache.camel.karavan.util;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Root record for the Camel component configuration.
+ * Since the JSON is an array, you would typically deserialize it as List<CamelComponentMetadata>
+ */
+public record CamelComponentMetadata(
+ ComponentDetails component,
+ Map<String, ComponentProperty> componentProperties,
+ Map<String, ComponentHeader> headers,
+ Map<String, ComponentProperty> properties
+) {
+ /**
+ * Record representing the "component" object in the JSON.
+ */
+ public record ComponentDetails(
+ String kind,
+ String name,
+ String title,
+ String description,
+ boolean deprecated,
+ String firstVersion,
+ String label,
+ String javaType,
+ String supportLevel,
+ String groupId,
+ String artifactId,
+ String version,
+ String scheme,
+ String extendsScheme,
+ String syntax,
+ boolean async,
+ boolean api,
+ boolean consumerOnly,
+ boolean producerOnly,
+ boolean lenientProperties,
+ boolean browsable,
+ boolean remote
+ ) {}
+
+ /**
+ * Record representing the individual properties inside "componentProperties" and "properties".
+ */
+ public record ComponentProperty(
+ int index,
+ String kind,
+ String displayName,
+ String group,
+ String label,
+ boolean required,
+ String type,
+ String javaType,
+
+ @JsonProperty("enum")
+ List<String> enumValues,
+
+ boolean deprecated,
+ String deprecationNote,
+ boolean autowired,
+ boolean secret,
+ Object defaultValue,
+ String configurationClass,
+ String configurationField,
+ String description,
+
+ // Additional optional fields found in advanced configurations
+ String optionalPrefix,
+ String prefix,
+ Boolean multiValue,
+ Boolean supportFileReference,
+ Boolean largeInput,
+ String inputLanguage
+ ) {}
+
+ /**
+ * Record representing the individual headers inside the "headers" object.
+ * Headers slightly differ from properties (e.g., they have 'constantName' and 'important', but no 'type').
+ */
+ public record ComponentHeader(
+ int index,
+ String kind,
+ String displayName,
+ String group,
+ String label,
+ boolean required,
+ String javaType,
+
+ @JsonProperty("enum")
+ List<String> enumValues,
+
+ boolean deprecated,
+ String deprecationNote,
+ boolean autowired,
+ boolean secret,
+ Object defaultValue,
+ String description,
+ String constantName,
+
+ // Additional optional fields specific to headers
+ Boolean important
+ ) {}
+}
+
diff --git a/karavan-app/src/main/java/org/apache/camel/karavan/util/PathUtils.java b/karavan-app/src/main/java/org/apache/camel/karavan/util/PathUtils.java
index 4558bb4d..0ecc1286 100644
--- a/karavan-app/src/main/java/org/apache/camel/karavan/util/PathUtils.java
+++ b/karavan-app/src/main/java/org/apache/camel/karavan/util/PathUtils.java
@@ -56,6 +56,38 @@ public final class PathUtils {
validateName("Project id", projectId);
}
+ /**
+ * Compiles a file name glob (only <code>*</code> and <code>?</code> wildcards are supported) into a regex.
+ * Every other character is matched literally, so a pattern can never escape a single path segment.
+ *
+ * @throws IllegalArgumentException if the pattern is empty or contains path separators
+ */
+ public static Pattern compileFileNameGlob(String glob) {
+ if (glob == null || glob.isBlank()) {
+ throw new IllegalArgumentException("Pattern cannot be empty");
+ }
+ if (glob.contains("/") || glob.contains("\\") || glob.indexOf('\0') >= 0) {
+ throw new IllegalArgumentException("Pattern contains path traversal characters: " + glob);
+ }
+ StringBuilder regex = new StringBuilder();
+ StringBuilder literal = new StringBuilder();
+ for (char c : glob.toCharArray()) {
+ if (c == '*' || c == '?') {
+ if (!literal.isEmpty()) {
+ regex.append(Pattern.quote(literal.toString()));
+ literal.setLength(0);
+ }
+ regex.append(c == '*' ? ".*" : ".");
+ } else {
+ literal.append(c);
+ }
+ }
+ if (!literal.isEmpty()) {
+ regex.append(Pattern.quote(literal.toString()));
+ }
+ return Pattern.compile(regex.toString());
+ }
+
/**
* Resolves a name against a base directory and guarantees that the result stays inside it.
*
diff --git a/karavan-app/src/main/resources/application.properties b/karavan-app/src/main/resources/application.properties
index 6bf3005a..52f1fd12 100644
--- a/karavan-app/src/main/resources/application.properties
+++ b/karavan-app/src/main/resources/application.properties
@@ -102,7 +102,7 @@ quarkus.cache.caffeine."docker-check".maximum-size=1
quarkus.quinoa.enable-spa-routing=true
quarkus.quinoa.ci=false
quarkus.quinoa.package-manager-install=true
-quarkus.quinoa.package-manager-install.node-version=24.11.1
+quarkus.quinoa.package-manager-install.node-version=24.21.0
quarkus.quinoa.dev-server.port=3003
quarkus.quinoa.dev-server.check-timeout=60000
quarkus.quinoa.ignored-path-prefixes=/ui,/public,/api/,/auth,/developer,/platform
diff --git a/karavan-app/src/main/webui/package-lock.json b/karavan-app/src/main/webui/package-lock.json
index c3f1539b..38b485d5 100644
--- a/karavan-app/src/main/webui/package-lock.json
+++ b/karavan-app/src/main/webui/package-lock.json
@@ -92,7 +92,6 @@
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.7",
"@babel/generator": "^7.29.7",
@@ -1260,7 +1259,6 @@
"integrity": "sha512-8QqtOQT5ACVlmsvKOJNEaWmRPmcojMOzCz4Hs2BGG/toAp/K38LcsMRyLp349glq5AzJbCEeimEoxaX6v/fLrA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/core": "^7.21.3",
"@svgr/babel-preset": "8.1.0",
@@ -1685,7 +1683,6 @@
"integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"undici-types": "~7.18.0"
}
@@ -1701,7 +1698,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
"license": "MIT",
- "peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -1785,7 +1781,6 @@
"integrity": "sha512-fUBfTuuEulWqX6V8+O3PtScV01tzYYRUDTAirHFKoRAt7nOzoGiPt0M/bB47wWNy0coOOcgEwAMUtBpykMxl6w==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.67.0",
"@typescript-eslint/types": "8.67.0",
@@ -2052,7 +2047,6 @@
"integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true,
"license": "MIT",
- "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -2235,7 +2229,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.11.12",
"caniuse-lite": "^1.0.30001809",
@@ -2819,7 +2812,6 @@
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
"license": "ISC",
- "peer": true,
"engines": {
"node": ">=12"
}
@@ -3147,7 +3139,6 @@
"integrity": "sha512-wqA7W2jbsC/BnV9Iv1UZpKVFkO1AdNoSmYW8NWG4HNOBbkAMvIqDZ27pI2f07dqn583NcIC44ckjAcOXDL1QbQ==",
"dev": true,
"license": "MIT",
- "peer": true,
"workspaces": [
"packages/*"
],
@@ -5448,7 +5439,6 @@
"resolved": "https://registry.npmjs.org/mobx/-/mobx-6.16.1.tgz",
"integrity": "sha512-syNcDdX3KT+Jq3je6eGjBhuc24Z68td2VG0zNFqRswaE433D9SNH5VRy/xrGbJsUixfppLLccXhAW9JSf6n+SQ==",
"license": "MIT",
- "peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/mobx"
@@ -5506,7 +5496,6 @@
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.56.0.tgz",
"integrity": "sha512-sXboRm3BeBeLm938eaiyLMe0OxzfXIlZvbv4ir/jVgQy1zDhWjgmny0WoN45fuDKhCCQsYMbBJrv/A6jd8aCUg==",
"license": "MIT",
- "peer": true,
"dependencies": {
"dompurify": "3.4.8",
"marked": "14.0.0"
@@ -5834,7 +5823,6 @@
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=12"
},
@@ -5970,7 +5958,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
"integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -5980,7 +5967,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
"integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -6631,7 +6617,6 @@
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"dev": true,
"license": "Apache-2.0",
- "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -6815,7 +6800,6 @@
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
"license": "MIT",
- "peer": true,
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
@@ -6896,7 +6880,6 @@
"integrity": "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.5",
diff --git a/karavan-app/src/main/webui/src/ui/page-project/ProjectPanel.tsx b/karavan-app/src/main/webui/src/ui/page-project/ProjectPanel.tsx
index 9d535535..a2b5b1ea 100644
--- a/karavan-app/src/main/webui/src/ui/page-project/ProjectPanel.tsx
+++ b/karavan-app/src/main/webui/src/ui/page-project/ProjectPanel.tsx
@@ -4,7 +4,6 @@ import {useFilesStore, useProjectStore} from '@stores/ProjectStore';
import {ProjectService} from '@services/ProjectService';
import {BUILD_IN_PROJECTS, ProjectType} from '@models/ProjectModels';
import {TopologyTab} from './project-topology/TopologyTab';
-import {CreateProjectModal} from './files/CreateProjectModal';
import {BeanWizard} from './beans/BeanWizard';
import {BuildTab} from './project-build/BuildTab';
import {SourcesTab} from './files/SourcesTab';
@@ -13,6 +12,7 @@ import {ProjectContainersContextProvider} from "./ProjectContainersContextProvid
import {ContainersTab} from "./project-containers/ContainersTab";
import "./ProjectPanel.css"
import {ProjectFunctionHook} from "./ProjectFunctionHook";
+import {CreateKameletModal} from "./files/CreateKameletModal";
function ProjectPanel() {
@@ -45,7 +45,7 @@ function ProjectPanel() {
return isTopology
? (<div className="project-architecture-page">
<TopologyTab/>
- <CreateProjectModal/>
+ <CreateKameletModal/>
<BeanWizard/>
</div>
)