index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/CommandUtils.java
/* * 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.installer; import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentCondition; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.fabric8.openshift.api.model.operatorhub.v1.Operator; import io.fabric8.openshift.client.OpenShiftClient; import org.apache.camel.karavan.installer.resources.*; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.stream.Collectors; public class CommandUtils { public static void installKaravan(KaravanCommand config) { try (KubernetesClient client = new KubernetesClientBuilder().build()) { OpenShiftClient oClient = client.adapt(OpenShiftClient.class); if (oClient.isSupported()) { System.out.println("⭕ Installing Karavan to OpenShift"); config.setOpenShift(true); } else { System.out.println("⭕ Installing Karavan to Kubernetes"); config.setOpenShift(false); } install(config, client); } } private static void install(KaravanCommand config, KubernetesClient client) { // Create namespace if (client.namespaces().withName(config.getNamespace()).get() == null) { Namespace ns = new NamespaceBuilder().withNewMetadata().withName(config.getNamespace()).endMetadata().build(); ns = client.namespaces().resource(ns).create(); log("Namespace " + ns.getMetadata().getName() + " created"); } else { log("Namespace " + config.getNamespace() + " already exists"); } // Check and install Infinispan if (!isInfinispanInstalled(client, config) && config.isInstallInfinispan()) { logError("Infinispan is not installed"); installInfinispan(config, client); } // Check and install Gitea if (config.isInstallGitea()) { installGitea(config, client); } // Check secrets if (!checkKaravanSecrets(config, client)) { logError("Karavan secrets not found"); // try to create secrets if (!tryToCreateKaravanSecrets(config, client)) { logPoint("Apply secrets before installation"); logPoint("Or provide Git, Auth and Image Registry options"); System.exit(0); } } else { log("Karavan secrets found"); } // Create Nexus Proxy if (config.isNexusProxy()) { createOrReplace(Nexus.getDeployment(config), client); createOrReplace(Nexus.getService(config), client); } // Create ConfigMap createOrReplace(KaravanConfigMap.getConfigMap(config), client); // Create Service Accounts createOrReplace(KaravanServiceAccount.getServiceAccount(config), client); // Create Roles and role bindings createOrReplace(KaravanRole.getRole(config), client); createOrReplace(KaravanRole.getRoleBinding(config), client); createOrReplace(KaravanRole.getRoleBindingView(config), client); // Create deployment createOrReplace(KaravanDeployment.getDeployment(config), client); // Create service createOrReplace(KaravanService.getService(config), client); if (config.isOpenShift()) { createOrReplace(KaravanService.getRoute(config), client); } log("Karavan is installed"); System.out.print("\uD83D\uDC2B Karavan is starting "); while (!checkKaravanReady(config, client)) { try { Thread.sleep(2000); } catch (Exception e) { } System.out.print("\uD83D\uDC2B "); } System.out.println(); log("Karavan is started"); } public static boolean checkKaravanSecrets(KaravanCommand config, KubernetesClient client) { Secret secret = client.secrets().inNamespace(config.getNamespace()).withName(Constants.NAME).get(); return secret != null; } public static boolean tryToCreateKaravanSecrets(KaravanCommand config, KubernetesClient client) { if (config.gitConfigured()) { if (config.getImageRegistry() == null) { if (config.isOpenShift()) { config.setImageRegistry(Constants.DEFAULT_IMAGE_REGISTRY_OPENSHIFT); } else { Service registryService = client.services().inNamespace("kube-system").withName("registry").get(); if (registryService != null) { config.setImageRegistry(registryService.getSpec().getClusterIP()); } else { logError("Set Image Registry parameters"); System.exit(0); } } } if ((config.isAuthOidc() && config.oidcConfigured()) || (config.isAuthBasic() && config.getMasterPassword() != null && config.getMasterPassword().isEmpty()) || (config.getAuth().equals("public"))) { Secret secret = KaravanSecret.getSecret(config); client.resource(secret).createOrReplace(); log("\uD83D\uDD11", "Karavan secret created"); return true; } } return false; } public static boolean checkKaravanReady(KaravanCommand config, KubernetesClient client) { Deployment deployment = client.apps().deployments().inNamespace(config.getNamespace()).withName(Constants.NAME).get(); Integer replicas = deployment.getStatus().getReplicas(); Integer ready = deployment.getStatus().getReadyReplicas(); Integer available = deployment.getStatus().getAvailableReplicas(); Optional<DeploymentCondition> condition = deployment.getStatus().getConditions().stream() .filter(c -> c.getType().equals("Available") && c.getStatus().equals("True")).findFirst(); return deployment.getStatus() != null && Objects.equals(replicas, ready) && Objects.equals(replicas, available) && condition.isPresent(); } private static <T extends HasMetadata> void createOrReplace(T is, KubernetesClient client) { try { T result = client.resource(is).createOrReplace(); log(result.getKind() + " " + result.getMetadata().getName() + " created"); } catch (Exception e) { logError(e.getLocalizedMessage()); } } private static void installInfinispan(KaravanCommand config, KubernetesClient client) { System.out.print("⏳ Installing Infinispan "); String yaml = getResourceFile("/infinispan.yaml"); String resource = yaml .replace("$INFINISPAN_PASSWORD", config.getInfinispanPassword()) .replace("$INFINISPAN_IMAGE", config.getInfinispanImage()); client.load(new ByteArrayInputStream(resource.getBytes())).inNamespace(config.getNamespace()) .create().forEach(hasMetadata -> System.out.print("\uD83D\uDC2B ")); System.out.println(); log("Infinispan is installed"); } private static void installGitea(KaravanCommand config, KubernetesClient client) { System.out.print("⏳ Installing Gitea "); Arrays.stream(new String[] { "init.yaml", "config.yaml", "deployment.yaml", "service.yaml" }).forEach(s -> { String yaml = getResourceFile("/gitea/" + s); client.load(new ByteArrayInputStream(yaml.getBytes())).inNamespace(config.getNamespace()) .create().forEach(hasMetadata -> System.out.print("\uD83D\uDC2B ")); }); System.out.println(); log("Gitea is installed"); } private static boolean isInfinispanInstalled(KubernetesClient client, KaravanCommand config) { Service service = client.services().inNamespace(config.getNamespace()).withName("infinispan").get(); StatefulSet set = client.apps().statefulSets().inNamespace(config.getNamespace()).withName("infinispan").get(); return service != null && set != null; } public static void log(String emoji, String message) { System.out.println(emoji + " " + message); } public static void log(String message) { System.out.println(getOkMessage(message)); } public static void logPoint(String message) { System.out.println(getPointMessage(message)); } public static void logError(String message) { System.out.println(getErrorMessage(message)); } private static String getOkMessage(String message) { return "\uD83D\uDC4D " + message; } private static String getPointMessage(String message) { return "\uD83D\uDC49 " + message; } private static String getErrorMessage(String message) { return "‼\uFE0F " + message; } private static boolean isOpenShift(KubernetesClient client) { return client.adapt(OpenShiftClient.class).isSupported(); } private static String getResourceFile(String path) { try { InputStream inputStream = CommandUtils.class.getResourceAsStream(path); return new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); } catch (Exception e) { return null; } } }
900
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/Constants.java
/* * 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.installer; public final class Constants { public static final String DEFAULT_NAMESPACE = "karavan"; public static final String DEFAULT_ENVIRONMENT = "dev"; public static final String DEFAULT_AUTH = "public"; public static final String DEFAULT_GIT_REPOSITORY = "http://gitea:3000/karavan/karavan.git"; public static final String DEFAULT_GIT_USERNAME = "karavan"; public static final String DEFAULT_GIT_PASSWORD = "karavan"; public static final String DEFAULT_GIT_BRANCH = "main"; public static final String DEFAULT_IMAGE_REGISTRY_OPENSHIFT = "image-registry.openshift-image-registry.svc:5000"; public static final String DEFAULT_DEVMODE_IMAGE = "ghcr.io/apache/camel-karavan-devmode"; public static final String KARAVAN_IMAGE = "ghcr.io/apache/camel-karavan"; public static final String INFINISPAN_IMAGE = "quay.io/infinispan/server:14.0.17.Final"; public static final String INFINISPAN_USERNAME = "admin"; public static final String INFINISPAN_PASSWORD = "karavan"; public static final String NAME = "karavan"; public static final String SERVICEACCOUNT_KARAVAN = "karavan"; public static final String ROLE_KARAVAN = "karavan"; public static final String ROLEBINDING_KARAVAN = "karavan-role-binding"; public static final String ROLEBINDING_KARAVAN_VIEW = "karavan-cluster-role-binding"; public static final String INFINISPAN_SECRET_NAME = "infinispan-secret"; }
901
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/resources/KaravanService.java
/* * 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.installer.resources; import io.fabric8.kubernetes.api.model.IntOrString; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServiceBuilder; import io.fabric8.kubernetes.api.model.ServicePortBuilder; import io.fabric8.openshift.api.model.Route; import io.fabric8.openshift.api.model.RouteBuilder; import io.fabric8.openshift.api.model.RoutePort; import io.fabric8.openshift.api.model.RouteTargetReferenceBuilder; import org.apache.camel.karavan.installer.Constants; import org.apache.camel.karavan.installer.KaravanCommand; import org.apache.camel.karavan.installer.ResourceUtils; import java.util.Map; public class KaravanService { public static Service getService(KaravanCommand config) { ServicePortBuilder portBuilder = new ServicePortBuilder() .withName("http").withPort(80).withProtocol("TCP").withTargetPort(new IntOrString(8080)); if (config.getNodePort() > 0) { portBuilder.withNodePort(config.getNodePort()); } return new ServiceBuilder() .withNewMetadata() .withName(Constants.NAME) .withNamespace(config.getNamespace()) .withLabels(ResourceUtils.getLabels(Constants.NAME, config.getVersion(), Map.of())) .endMetadata() .withNewSpec() .withType(config.getNodePort() > 0 ? "NodePort" : "ClusterIP") .withPorts(portBuilder.build()) .withSelector(Map.of("app", Constants.NAME)) .endSpec() .build(); } public static Route getRoute(KaravanCommand config) { return new RouteBuilder() .withNewMetadata() .withName(Constants.NAME) .withNamespace(config.getNamespace()) .withLabels(ResourceUtils.getLabels(Constants.NAME, config.getVersion(), Map.of())) .endMetadata() .withNewSpec() .withPort(new RoutePort(new IntOrString(8080))) .withTo(new RouteTargetReferenceBuilder().withKind("Service").withName(Constants.NAME).build()) .endSpec() .build(); } }
902
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/resources/KaravanRole.java
/* * 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.installer.resources; import io.fabric8.kubernetes.api.model.rbac.*; import org.apache.camel.karavan.installer.Constants; import org.apache.camel.karavan.installer.KaravanCommand; public class KaravanRole { public static Role getRole(KaravanCommand config) { return new RoleBuilder() .withNewMetadata() .withName(Constants.ROLE_KARAVAN) .withNamespace(config.getNamespace()) .endMetadata() .withRules( new PolicyRuleBuilder().withApiGroups("").withResources("secrets", "configmaps").withVerbs("*").build(), new PolicyRuleBuilder().withApiGroups("").withResources("persistentvolumes", "persistentvolumeclaims").withVerbs("*").build(), new PolicyRuleBuilder().withApiGroups("").withResources("pods", "services", "replicationcontrollers").withVerbs("*").build(), new PolicyRuleBuilder().withApiGroups("").withResources("endpoints", "ingresses", "ingressclasses", "endpointslices").withVerbs("*").build(), new PolicyRuleBuilder().withApiGroups("apps").withResources("deployments").withVerbs("*").build(), new PolicyRuleBuilder().withApiGroups("route.openshift.io").withResources("routes").withVerbs("*").build(), new PolicyRuleBuilder().withApiGroups("", "image.openshift.io").withResources("imagestreams/layers").withVerbs("get", "update").build() ) .build(); } public static RoleBinding getRoleBinding(KaravanCommand config) { return new RoleBindingBuilder() .withNewMetadata() .withName(Constants.ROLEBINDING_KARAVAN) .withNamespace(config.getNamespace()) .endMetadata() .withNewRoleRef("rbac.authorization.k8s.io", "Role", Constants.ROLE_KARAVAN) .withSubjects(new Subject("", "ServiceAccount", Constants.SERVICEACCOUNT_KARAVAN, config.getNamespace())) .build(); } public static RoleBinding getRoleBindingView(KaravanCommand config) { return new RoleBindingBuilder() .withNewMetadata() .withName(Constants.ROLEBINDING_KARAVAN_VIEW) .withNamespace(config.getNamespace()) .endMetadata() .withNewRoleRef("rbac.authorization.k8s.io", "ClusterRole", "view") .withSubjects(new Subject("", "ServiceAccount", Constants.SERVICEACCOUNT_KARAVAN, config.getNamespace())) .build(); } }
903
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/resources/KaravanSecret.java
/* * 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.installer.resources; import io.fabric8.kubernetes.api.model.*; import org.apache.camel.karavan.installer.Constants; import org.apache.camel.karavan.installer.KaravanCommand; import org.apache.camel.karavan.installer.ResourceUtils; import java.util.HashMap; import java.util.Map; public class KaravanSecret { public static Secret getSecret(KaravanCommand config) { Map<String, String> secretData = new HashMap<>(); secretData.put("master-password", (config.isAuthBasic() ? config.getMasterPassword() : "karavan")); secretData.put("oidc-secret", (config.isAuthOidc() ? config.getOidcSecret() : "xxx")); secretData.put("oidc-server-url", (config.isAuthOidc() ? config.getOidcServerUrl() : "https://localhost/auth/realms/karavan")); secretData.put("oidc-frontend-url", (config.isAuthOidc() ? config.getOidcFrontendUrl() : "https://localhost/auth")); secretData.put("git-repository", config.getGitRepository()); secretData.put("git-password", config.getGitPassword()); secretData.put("git-username", config.getGitUsername()); secretData.put("git-branch", config.getGitBranch()); secretData.put("image-registry", config.getImageRegistry()); secretData.put("image-group", config.getImageGroup()); secretData.put("image-registry-username", config.getImageRegistryUsername()); secretData.put("image-registry-password", config.getImageRegistryPassword()); return new SecretBuilder() .withNewMetadata() .withName(Constants.NAME) .withNamespace(config.getNamespace()) .withLabels(ResourceUtils.getLabels(Constants.NAME, config.getVersion(), Map.of())) .endMetadata() .withStringData(secretData) .build(); } }
904
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/resources/KaravanDeployment.java
/* * 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.installer.resources; import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import org.apache.camel.karavan.installer.Constants; import org.apache.camel.karavan.installer.KaravanCommand; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import static org.apache.camel.karavan.installer.Constants.INFINISPAN_SECRET_NAME; import static org.apache.camel.karavan.installer.Constants.NAME; public class KaravanDeployment { public static Deployment getDeployment(KaravanCommand config) { String baseImage = config.getBaseImage(); String image = baseImage + ":" + config.getVersion(); List<EnvVar> envVarList = new ArrayList<>(); envVarList.add( new EnvVar("KARAVAN_ENVIRONMENT", config.getEnvironment(), null) ); envVarList.add( new EnvVar("KARAVAN_CONTAINER_STATUS_INTERVAL", "disabled", null) ); envVarList.add( new EnvVar("KARAVAN_CONTAINER_STATISTICS_INTERVAL", "disabled", null) ); envVarList.add( new EnvVar("KARAVAN_CAMEL_STATUS_INTERVAL", "3s", null) ); envVarList.add( new EnvVar("KARAVAN_DEVMODE_IMAGE", config.getDevmodeImage(), null) ); envVarList.add( new EnvVar("INFINISPAN_HOSTS", "infinispan." + config.getNamespace() + ":11222", null) ); envVarList.add( new EnvVar("INFINISPAN_PASSWORD", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("password", INFINISPAN_SECRET_NAME, false)).build()) ); envVarList.add( new EnvVar("KUBERNETES_NAMESPACE", null, new EnvVarSourceBuilder().withFieldRef(new ObjectFieldSelector("", "metadata.namespace")).build()) ); String auth = config.getAuth(); if (Objects.equals(auth, "basic")) { image = baseImage + "-basic:" + config.getVersion(); envVarList.add( new EnvVar("MASTER_PASSWORD", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("master-password", NAME, false)).build()) ); } else if (Objects.equals(auth, "oidc")) { image = baseImage + "-oidc:" + config.getVersion(); envVarList.add( new EnvVar("OIDC_FRONTEND_URL", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("oidc-frontend-url", "karavan", false)).build()) ); envVarList.add( new EnvVar("OIDC_SERVER_URL", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("oidc-server-url", "karavan", false)).build()) ); envVarList.add( new EnvVar("OIDC_SECRET", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("oidc-secret", "karavan", false)).build()) ); } if (config.isInstallGitea()) { envVarList.add( new EnvVar("KARAVAN_GIT_INSTALL_GITEA", "true", null) ); } Map<String, String> labels = config.getLabels(); labels.put("app.kubernetes.io/runtime", "quarkus"); return new DeploymentBuilder() .withNewMetadata() .withName(Constants.NAME) .withNamespace(config.getNamespace()) .withLabels(labels) .endMetadata() .withNewSpec() .withReplicas(1) .withNewSelector() .addToMatchLabels(Map.of("app", Constants.NAME)) .endSelector() .withNewTemplate() .withNewMetadata() .addToLabels(Map.of("app", Constants.NAME)) .endMetadata() .withNewSpec() .addNewContainer() .withName(Constants.NAME) .withImage(image) .withImagePullPolicy("Always") .withEnv(envVarList) .addNewPort() .withContainerPort(8080) .withName(Constants.NAME) .endPort() .withResources(new ResourceRequirementsBuilder().withRequests( Map.of("memory", new Quantity("512Mi"))).build()) .endContainer() .withServiceAccount(Constants.SERVICEACCOUNT_KARAVAN) .endSpec() .endTemplate() .endSpec() .build(); } }
905
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/resources/KaravanConfigMap.java
/* * 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.installer.resources; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import org.apache.camel.karavan.installer.Constants; import org.apache.camel.karavan.installer.KaravanCommand; import org.apache.camel.karavan.installer.ResourceUtils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import java.util.stream.Collectors; public class KaravanConfigMap { private static final String MAVEN_URL = "<url>https://repo.maven.apache.org/maven2/</url>"; public static ConfigMap getConfigMap(KaravanCommand config) { String xml = getXml(config); return new ConfigMapBuilder() .withNewMetadata() .withName(Constants.NAME) .withNamespace(config.getNamespace()) .withLabels(ResourceUtils.getLabels(Constants.NAME, config.getVersion(), Map.of())) .endMetadata() .withData(Map.of("maven-settings.xml", xml)) .build(); } private static String getXml(KaravanCommand config) { try { InputStream inputStream = KaravanConfigMap.class.getResourceAsStream("/settings.xml"); return new BufferedReader(new InputStreamReader(inputStream)) .lines() .map(s -> { if (config.isNexusProxy() && s.contains(MAVEN_URL)) { return s.replace("namespace", config.getNamespace()); } else { return s; } }) .collect(Collectors.joining(System.getProperty("line.separator"))); } catch (Exception e) { return null; } } }
906
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/resources/KaravanServiceAccount.java
/* * 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.installer.resources; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.ServiceAccountBuilder; import org.apache.camel.karavan.installer.Constants; import org.apache.camel.karavan.installer.KaravanCommand; import org.apache.camel.karavan.installer.ResourceUtils; import java.util.Map; public class KaravanServiceAccount { public static ServiceAccount getServiceAccount(KaravanCommand config) { return new ServiceAccountBuilder() .withNewMetadata() .withName(Constants.SERVICEACCOUNT_KARAVAN) .withNamespace(config.getNamespace()) .withLabels(ResourceUtils.getLabels(Constants.SERVICEACCOUNT_KARAVAN, config.getVersion(), Map.of())) .endMetadata() .build(); } }
907
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/resources/Nexus.java
/* * 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.installer.resources; import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import org.apache.camel.karavan.installer.Constants; import org.apache.camel.karavan.installer.KaravanCommand; import java.util.Map; public class Nexus { public static final String NEXUS_NAME = "nexus"; public static final String NEXUS_IMAGE = "sonatype/nexus3"; public static final String NEXUS_DATA = "nexus-data"; public static final int NEXUS_PORT = 8081; public static Service getService(KaravanCommand config) { ServicePortBuilder portBuilder = new ServicePortBuilder() .withPort(80) .withProtocol("TCP") .withTargetPort(new IntOrString(NEXUS_PORT)); return new ServiceBuilder() .withNewMetadata() .withName(NEXUS_NAME) .withNamespace(config.getNamespace()) .endMetadata() .withNewSpec() .withSelector(Map.of("app", NEXUS_NAME)) .withPorts(portBuilder.build()) .endSpec() .build(); } public static Deployment getDeployment (KaravanCommand config) { return new DeploymentBuilder() .withNewMetadata() .withName(NEXUS_NAME) .withNamespace(config.getNamespace()) .endMetadata() .withNewSpec() .withNewSelector() .addToMatchLabels(Map.of("app", NEXUS_NAME)) .endSelector() .withNewTemplate() .withNewMetadata() .addToLabels(Map.of("app", NEXUS_NAME)) .endMetadata() .withNewSpec() .addNewContainer() .withName(NEXUS_NAME) .withImage(NEXUS_IMAGE) .withImagePullPolicy("Always") .addNewPort() .withContainerPort(NEXUS_PORT) .withName("8081-tcp") .endPort() .withVolumeMounts( new VolumeMountBuilder().withName(NEXUS_DATA).withMountPath("/" + NEXUS_DATA).build() ) .withLivenessProbe( new ProbeBuilder() .withHttpGet(new HTTPGetActionBuilder() .withPath("/service/rest/v1/status") .withPort(new IntOrString(NEXUS_PORT)) .build()) .withInitialDelaySeconds(90) .withPeriodSeconds(3) .build()) .withReadinessProbe( new ProbeBuilder() .withHttpGet(new HTTPGetActionBuilder() .withPath("/service/rest/v1/status") .withPort(new IntOrString(NEXUS_PORT)) .build()) .withInitialDelaySeconds(90) .withPeriodSeconds(3) .build()) .endContainer() .withServiceAccount(Constants.NAME) .withVolumes( new VolumeBuilder().withName(NEXUS_DATA).withEmptyDir(new EmptyDirVolumeSource()).build() ) .endSpec() .endTemplate() .endSpec() .build(); } }
908
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/resources
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/resources/snippets/org.apache.camel.Processor.java
import org.apache.camel.BindToRegistry; import org.apache.camel.Configuration; import org.apache.camel.Exchange; import org.apache.camel.Processor; @Configuration @BindToRegistry("NAME") public class NAME implements Processor { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); } }
909
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/resources
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/resources/snippets/org.apache.camel.AggregationStrategy.java
import org.apache.camel.AggregationStrategy; import org.apache.camel.Configuration; import org.apache.camel.BindToRegistry; import org.apache.camel.Exchange; @Configuration @BindToRegistry("NAME") public class NAME implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange == null) { return newExchange; } String oldBody = oldExchange.getIn().getBody(String.class); String newBody = newExchange.getIn().getBody(String.class); oldExchange.getIn().setBody(oldBody + "+" + newBody); return oldExchange; } }
910
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerEventListener.java
/* * 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.docker; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.Event; import com.github.dockerjava.api.model.EventType; import io.vertx.core.eventbus.EventBus; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.io.Closeable; import java.io.IOException; import java.util.Objects; import java.util.Optional; import static org.apache.camel.karavan.shared.Constants.*; @ApplicationScoped public class DockerEventListener implements ResultCallback<Event> { @Inject DockerService dockerService; @Inject DockerForKaravan dockerForKaravan; @Inject InfinispanService infinispanService; private static final Logger LOGGER = Logger.getLogger(DockerEventListener.class.getName()); @Override public void onStart(Closeable closeable) { LOGGER.info("DockerEventListener started"); } @Override public void onNext(Event event) { try { if (Objects.equals(event.getType(), EventType.CONTAINER)) { Container container = dockerService.getContainer(event.getId()); if (container != null) { onContainerEvent(event, container); } } } catch (Exception exception) { LOGGER.error(exception.getMessage()); } } public void onContainerEvent(Event event, Container container) throws InterruptedException { if (infinispanService.isReady()) { if ("exited".equalsIgnoreCase(container.getState()) && Objects.equals(container.getLabels().get(LABEL_TYPE), ContainerStatus.ContainerType.build.name())) { String tag = container.getLabels().get(LABEL_TAG); String projectId = container.getLabels().get(LABEL_PROJECT_ID); dockerForKaravan.syncImage(projectId, tag); } } } @Override public void onError(Throwable throwable) { LOGGER.error(throwable.getMessage()); } @Override public void onComplete() { LOGGER.error("DockerEventListener complete"); } @Override public void close() throws IOException { LOGGER.info("DockerEventListener close"); } }
911
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerService.java
/* * 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.docker; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.*; import com.github.dockerjava.api.model.*; import com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.DockerClientImpl; import com.github.dockerjava.core.InvocationBuilder; import com.github.dockerjava.transport.DockerHttpClient; import com.github.dockerjava.zerodep.ZerodepDockerHttpClient; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.code.CodeService; import org.apache.camel.karavan.code.model.DockerComposeService; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.shared.Constants; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.io.IOUtils; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import static org.apache.camel.karavan.shared.Constants.*; @ApplicationScoped public class DockerService extends DockerServiceUtils { private static final Logger LOGGER = Logger.getLogger(DockerService.class.getName()); protected static final String NETWORK_NAME = "karavan"; @ConfigProperty(name = "karavan.environment") String environment; @Inject DockerEventListener dockerEventListener; @Inject CodeService codeService; @Inject Vertx vertx; private DockerClient dockerClient; public boolean checkDocker() { try { getDockerClient().pingCmd().exec(); LOGGER.info("Docker is available"); return true; } catch (Exception e) { LOGGER.error("Error connecting Docker: " + e.getMessage()); return false; } } public Info getInfo(){ return getDockerClient().infoCmd().exec(); } public List<ContainerStatus> collectContainersStatuses() { List<ContainerStatus> result = new ArrayList<>(); getDockerClient().listContainersCmd().withShowAll(true).exec().forEach(container -> { ContainerStatus containerStatus = getContainerStatus(container, environment); result.add(containerStatus); }); return result; } public List<ContainerStatus> collectContainersStatistics() { List<ContainerStatus> result = new ArrayList<>(); getDockerClient().listContainersCmd().withShowAll(true).exec().forEach(container -> { ContainerStatus containerStatus = getContainerStatus(container, environment); Statistics stats = getContainerStats(container.getId()); updateStatistics(containerStatus, stats); result.add(containerStatus); }); return result; } public void startListeners() { getDockerClient().eventsCmd().exec(dockerEventListener); } public void stopListeners() throws IOException { dockerEventListener.close(); } public void createNetwork() { if (!getDockerClient().listNetworksCmd().exec().stream() .filter(n -> n.getName().equals(NETWORK_NAME)) .findFirst().isPresent()) { CreateNetworkResponse res = getDockerClient().createNetworkCmd() .withName(NETWORK_NAME) .withDriver("bridge") .withInternal(false) .withAttachable(true).exec(); LOGGER.info("Network created: " + NETWORK_NAME); } else { LOGGER.info("Network already exists with name: " + NETWORK_NAME); } } public Container getContainer(String id) { List<Container> containers = getDockerClient().listContainersCmd().withShowAll(true).withIdFilter(List.of(id)).exec(); return containers.isEmpty() ? null : containers.get(0); } public Container getContainerByName(String name) { List<Container> containers = findContainer(name); return containers.size() > 0 ? containers.get(0) : null; } public Statistics getContainerStats(String containerId) { InvocationBuilder.AsyncResultCallback<Statistics> callback = new InvocationBuilder.AsyncResultCallback<>(); getDockerClient().statsCmd(containerId).withContainerId(containerId).withNoStream(true).exec(callback); Statistics stats = null; try { stats = callback.awaitResult(); callback.close(); } catch (RuntimeException | IOException e) { // you may want to throw an exception here } return stats; } public Container createContainerFromCompose(DockerComposeService compose, ContainerStatus.ContainerType type) throws InterruptedException { Map<String,String> labels = new HashMap<>(); labels.put(LABEL_TYPE, type.name()); return createContainerFromCompose(compose, labels); } public Container createContainerFromCompose(DockerComposeService compose, Map<String, String> labels) throws InterruptedException { List<Container> containers = findContainer(compose.getContainer_name()); if (containers.isEmpty()) { LOGGER.infof("Compose Service starting for %s", compose.getContainer_name()); HealthCheck healthCheck = getHealthCheck(compose.getHealthcheck()); List<String> env = compose.getEnvironment() != null ? compose.getEnvironmentList() : List.of(); LOGGER.infof("Compose Service started for %s", compose.getContainer_name()); RestartPolicy restartPolicy = RestartPolicy.noRestart(); if (Objects.equals(compose.getRestart(), RestartPolicy.onFailureRestart(10).getName())) { restartPolicy = RestartPolicy.onFailureRestart(10); } else if (Objects.equals(compose.getRestart(), RestartPolicy.alwaysRestart().getName())) { restartPolicy = RestartPolicy.alwaysRestart(); } return createContainer(compose.getContainer_name(), compose.getImage(), env, compose.getPortsMap(), healthCheck, labels, Map.of(), NETWORK_NAME, restartPolicy); } else { LOGGER.info("Compose Service already exists: " + containers.get(0).getId()); return containers.get(0); } } public List<Container> findContainer(String containerName) { return getDockerClient().listContainersCmd().withShowAll(true).withNameFilter(List.of(containerName)).exec() .stream().filter(c -> Objects.equals(c.getNames()[0].replaceFirst("/", ""), containerName)).toList(); } public Container createContainer(String name, String image, List<String> env, Map<Integer, Integer> ports, HealthCheck healthCheck, Map<String, String> labels, Map<String, String> volumes, String network, RestartPolicy restartPolicy, String... command) throws InterruptedException { List<Container> containers = findContainer(name); if (containers.size() == 0) { pullImage(image); CreateContainerCmd createContainerCmd = getDockerClient().createContainerCmd(image) .withName(name).withLabels(labels).withEnv(env).withHostName(name).withHealthcheck(healthCheck); Ports portBindings = getPortBindings(ports); List<Mount> mounts = new ArrayList<>(); if (volumes != null && !volumes.isEmpty()) { volumes.forEach((hostPath, containerPath) -> { mounts.add(new Mount().withType(MountType.BIND).withSource(hostPath).withTarget(containerPath)); }); } if (command.length > 0) { createContainerCmd.withCmd(command); } if (Objects.equals(labels.get(LABEL_PROJECT_ID), ContainerStatus.ContainerType.build.name())) { mounts.add(new Mount().withType(MountType.BIND).withSource("/var/run/docker.sock").withTarget("/var/run/docker.sock")); } createContainerCmd.withHostConfig(new HostConfig() .withRestartPolicy(restartPolicy) .withPortBindings(portBindings) .withMounts(mounts) .withNetworkMode(network != null ? network : NETWORK_NAME)); CreateContainerResponse response = createContainerCmd.exec(); LOGGER.info("Container created: " + response.getId()); return getDockerClient().listContainersCmd().withShowAll(true) .withIdFilter(Collections.singleton(response.getId())).exec().get(0); } else { LOGGER.info("Container already exists: " + containers.get(0).getId()); return containers.get(0); } } public void runContainer(String name) { List<Container> containers = findContainer(name); if (containers.size() == 1) { runContainer(containers.get(0)); } } public void runContainer(Container container) { if (container.getState().equals("paused")) { getDockerClient().unpauseContainerCmd(container.getId()).exec(); } else if (!container.getState().equals("running")) { getDockerClient().startContainerCmd(container.getId()).exec(); } } public void execCommandInContainer(Container container, String... cmd) { getDockerClient().execCreateCmd(container.getId()).withCmd(cmd).exec(); } public List<Container> listContainers(Boolean showAll) { return getDockerClient().listContainersCmd().withShowAll(showAll).exec(); } public List<InspectVolumeResponse> listVolumes() { return getDockerClient().listVolumesCmd().exec().getVolumes(); } public InspectVolumeResponse getVolume(String name) { return getDockerClient().inspectVolumeCmd(name).exec(); } public CreateVolumeResponse createVolume(String name) { return getDockerClient().createVolumeCmd().withName(name).exec(); } public InspectContainerResponse inspectContainer(String id) { return getDockerClient().inspectContainerCmd(id).exec(); } public ExecCreateCmdResponse execCreate(String id, String... cmd) { return getDockerClient().execCreateCmd(id) .withAttachStdout(true).withAttachStderr(true) .withCmd(cmd) .exec(); } public void execStart(String id, ResultCallback.Adapter<Frame> callBack) throws InterruptedException { dockerClient.execStartCmd(id).exec(callBack).awaitCompletion(); } public void copyFiles(String containerId, String containerPath, Map<String, String> files) throws IOException { String temp = codeService.saveProjectFilesInTemp(files); System.out.println(temp); dockerClient.copyArchiveToContainerCmd(containerId).withRemotePath(containerPath) .withDirChildrenOnly(true).withHostResource(temp).exec(); } public void copyExecFile(String containerId, String containerPath, String filename, String script) { String temp = vertx.fileSystem().createTempDirectoryBlocking(containerId); String path = temp + File.separator + filename; vertx.fileSystem().writeFileBlocking(path, Buffer.buffer(script)); try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(byteArrayOutputStream)) { tarArchive.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); tarArchive.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); TarArchiveEntry tarEntry = new TarArchiveEntry(new File(path)); tarEntry.setName(filename); tarEntry.setMode(0755); tarArchive.putArchiveEntry(tarEntry); IOUtils.write(Files.readAllBytes(Paths.get(path)), tarArchive); tarArchive.closeArchiveEntry(); tarArchive.finish(); dockerClient.copyArchiveToContainerCmd(containerId) .withTarInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())) .withRemotePath(containerPath).exec(); } catch (Exception e) { LOGGER.error(e.getMessage()); e.printStackTrace(); } } public void logContainer(String containerName, LogCallback callback) { try { Container container = getContainerByName(containerName); if (container != null) { getDockerClient().logContainerCmd(container.getId()) .withStdOut(true) .withStdErr(true) .withTimestamps(false) .withFollowStream(true) .withTailAll() .exec(callback); callback.awaitCompletion(); } } catch (Exception e) { LOGGER.error(e.getMessage()); } } public void pauseContainer(String name) { List<Container> containers = findContainer(name); if (containers.size() == 1) { Container container = containers.get(0); if (container.getState().equals("running")) { getDockerClient().pauseContainerCmd(container.getId()).exec(); } } } public void stopContainer(String name) { List<Container> containers = findContainer(name); if (containers.size() == 1) { Container container = containers.get(0); if (container.getState().equals("running")) { getDockerClient().stopContainerCmd(container.getId()).exec(); } } } public void deleteContainer(String name) { List<Container> containers = findContainer(name); if (containers.size() == 1) { Container container = containers.get(0); getDockerClient().removeContainerCmd(container.getId()).withForce(true).exec(); } } public void pullImage(String image) throws InterruptedException { List<Image> images = getDockerClient().listImagesCmd().withShowAll(true).exec(); List<String> tags = images.stream() .map(i -> Arrays.stream(i.getRepoTags()).collect(Collectors.toList())) .flatMap(Collection::stream) .toList(); if (!images.stream().anyMatch(i -> tags.contains(image))) { ResultCallback.Adapter<PullResponseItem> pull = getDockerClient().pullImageCmd(image).start().awaitCompletion(); } } private DockerClientConfig getDockerClientConfig() { DefaultDockerClientConfig.Builder builder = DefaultDockerClientConfig.createDefaultConfigBuilder(); return builder.build(); } private DockerHttpClient getDockerHttpClient(DockerClientConfig config) { return new ZerodepDockerHttpClient.Builder() .dockerHost(config.getDockerHost()) .sslConfig(config.getSSLConfig()) .maxConnections(100) .build(); } public DockerClient getDockerClient() { if (dockerClient == null) { DockerClientConfig config = getDockerClientConfig(); DockerHttpClient httpClient = getDockerHttpClient(config); dockerClient = DockerClientImpl.getInstance(config, httpClient); } return dockerClient; } public int getMaxPortMapped(int port) { return getDockerClient().listContainersCmd().withShowAll(true).exec().stream() .map(c -> List.of(c.ports)) .flatMap(java.util.List::stream) .filter(p -> Objects.equals(p.getPrivatePort(), port)) .map(ContainerPort::getPublicPort).filter(Objects::nonNull) .mapToInt(Integer::intValue) .max().orElse(port); } public List<String> getImages() { return getDockerClient().listImagesCmd().withShowAll(true).exec().stream() .filter(image -> image != null && image.getRepoTags() != null && image.getRepoTags().length > 0) .map(image -> image.getRepoTags()[0]).toList(); } public void deleteImage(String imageName) { Optional<Image> image = getDockerClient().listImagesCmd().withShowAll(true).exec().stream() .filter(i -> Arrays.stream(i.getRepoTags()).anyMatch(s -> Objects.equals(s, imageName))).findFirst(); if (image.isPresent()) { getDockerClient().removeImageCmd(image.get().getId()).exec(); } } }
912
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/LogCallback.java
/* * 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.docker; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.model.Frame; import java.util.function.Consumer; public class LogCallback extends ResultCallback.Adapter<Frame> { private final Consumer<String> action; public LogCallback(Consumer<String> action) { this.action = action; } @Override public void onNext(Frame frame) { action.accept(new String(frame.getPayload())); } }
913
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForInfinispan.java
/* * 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.docker; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.code.CodeService; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; @ApplicationScoped public class DockerForInfinispan { private static final Logger LOGGER = Logger.getLogger(DockerForInfinispan.class.getName()); protected static final String INFINISPAN_CONTAINER_NAME = "infinispan"; @ConfigProperty(name = "karavan.infinispan.username") String infinispanUsername; @ConfigProperty(name = "karavan.infinispan.password") String infinispanPassword; @Inject DockerService dockerService; @Inject CodeService codeService; public void startInfinispan() { try { LOGGER.info("Infinispan is starting..."); var compose = codeService.getInternalDockerComposeService(INFINISPAN_CONTAINER_NAME); compose.addEnvironment("USER", infinispanUsername); compose.addEnvironment("PASS", infinispanPassword); dockerService.createContainerFromCompose(compose, ContainerStatus.ContainerType.internal); dockerService.runContainer(INFINISPAN_CONTAINER_NAME); LOGGER.info("Infinispan is started"); } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
914
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForRegistry.java
/* * 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.docker; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.code.CodeService; import org.jboss.logging.Logger; @ApplicationScoped public class DockerForRegistry { private static final Logger LOGGER = Logger.getLogger(DockerForRegistry.class.getName()); protected static final String REGISTRY_CONTAINER_NAME = "registry"; @Inject DockerService dockerService; @Inject CodeService codeService; public void startRegistry() { try { LOGGER.info("Registry is starting..."); var compose = codeService.getInternalDockerComposeService(REGISTRY_CONTAINER_NAME); dockerService.createContainerFromCompose(compose, ContainerStatus.ContainerType.internal); dockerService.runContainer(REGISTRY_CONTAINER_NAME); LOGGER.info("Registry is started"); } catch (Exception e) { LOGGER.error(e.getCause().getMessage()); } } }
915
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForKaravan.java
/* * 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.docker; import com.github.dockerjava.api.model.Container; import com.github.dockerjava.api.model.HealthCheck; import com.github.dockerjava.api.model.RestartPolicy; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.infinispan.model.Project; import org.apache.camel.karavan.registry.RegistryService; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.util.List; import java.util.Map; import java.util.Optional; import static org.apache.camel.karavan.shared.Constants.*; @ApplicationScoped public class DockerForKaravan { private static final Logger LOGGER = Logger.getLogger(DockerForKaravan.class.getName()); @ConfigProperty(name = "karavan.devmode.image") String devmodeImage; @ConfigProperty(name = "karavan.maven.cache") Optional<String> mavenCache; @Inject DockerService dockerService; @Inject RegistryService registryService; public void runProjectInDevMode(String projectId, String jBangOptions, Map<Integer, Integer> ports, Map<String, String> files) throws Exception { Map<String, String> volumes = getMavenVolumes(); Container c = createDevmodeContainer(projectId, jBangOptions, ports, volumes); dockerService.runContainer(projectId); dockerService.copyFiles(c.getId(), "/karavan/code", files); } protected Container createDevmodeContainer(String projectId, String jBangOptions, Map<Integer, Integer> ports, Map<String, String> volumes) throws InterruptedException { LOGGER.infof("DevMode starting for %s with JBANG_OPTIONS=%s", projectId, jBangOptions); HealthCheck healthCheck = new HealthCheck().withTest(List.of("CMD", "curl", "-f", "http://localhost:8080/q/dev/health")) .withInterval(10000000000L).withTimeout(10000000000L).withStartPeriod(10000000000L).withRetries(30); List<String> env = jBangOptions != null && !jBangOptions.trim().isEmpty() ? List.of(ENV_VAR_JBANG_OPTIONS + "=" + jBangOptions) : List.of(); return dockerService.createContainer(projectId, devmodeImage, env, ports, healthCheck, Map.of(LABEL_TYPE, ContainerStatus.ContainerType.devmode.name(), LABEL_PROJECT_ID, projectId, LABEL_CAMEL_RUNTIME, CamelRuntime.CAMEL_MAIN.getValue() ), volumes, null, RestartPolicy.noRestart()); } public void runBuildProject(Project project, String script, List<String> env, String tag) throws Exception { String containerName = project.getProjectId() + BUILDER_SUFFIX; Map<String, String> volumes = getMavenVolumes(); dockerService.deleteContainer(containerName); Container c = createBuildContainer(containerName, project, env, volumes, tag); dockerService.copyExecFile(c.getId(), "/karavan/builder", "build.sh", script); dockerService.runContainer(c); } protected Container createBuildContainer(String containerName, Project project, List<String> env, Map<String, String> volumes, String tag) throws InterruptedException { LOGGER.infof("Starting Build Container ", containerName); return dockerService.createContainer(containerName, devmodeImage, env, Map.of(), new HealthCheck(), Map.of( LABEL_TYPE, ContainerStatus.ContainerType.build.name(), LABEL_PROJECT_ID, project.getProjectId(), LABEL_TAG, tag ), volumes, null,RestartPolicy.noRestart(), "/karavan/builder/build.sh"); } private Map<String,String> getMavenVolumes(){ return mavenCache.map(s -> Map.of(s, "/karavan/.m2")).orElseGet(Map::of); } public void syncImage(String projectId, String tag) throws InterruptedException { String image = registryService.getRegistryWithGroupForSync() + "/" + projectId + ":" + tag; dockerService.pullImage(image); } }
916
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/LoggerCallback.java
/* * 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.docker; import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.model.Frame; import org.jboss.logging.Logger; public class LoggerCallback extends ResultCallback.Adapter<Frame> { private static final Logger LOGGER = Logger.getLogger(LoggerCallback.class.getName()); @Override public void onNext(Frame frame) { LOGGER.info(new String(frame.getPayload())); } @Override public void onError(Throwable throwable) { LOGGER.error(throwable.getMessage()); } }
917
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerForGitea.java
/* * 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.docker; import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.model.Container; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.git.model.GitConfig; import org.apache.camel.karavan.code.CodeService; import org.apache.camel.karavan.git.GitService; import org.apache.camel.karavan.git.GiteaService; import org.jboss.logging.Logger; @ApplicationScoped public class DockerForGitea { private static final Logger LOGGER = Logger.getLogger(DockerForGitea.class.getName()); protected static final String GITEA_CONTAINER_NAME = "gitea"; @Inject DockerService dockerService; @Inject GiteaService giteaService; @Inject GitService gitService; @Inject CodeService codeService; public void startGitea() { try { LOGGER.info("Gitea container is starting..."); var compose = codeService.getInternalDockerComposeService(GITEA_CONTAINER_NAME); Container c = dockerService.createContainerFromCompose(compose, ContainerStatus.ContainerType.internal); dockerService.runContainer(GITEA_CONTAINER_NAME); LOGGER.info("Gitea container is started"); } catch (Exception e) { LOGGER.error(e.getMessage()); } } public void createGiteaUser() { try { LOGGER.info("Creating Gitea User"); GitConfig config = gitService.getGitConfig(); Container gitea = dockerService.getContainerByName(GITEA_CONTAINER_NAME); ExecCreateCmdResponse user = dockerService.execCreate(gitea.getId(), "/app/gitea/gitea", "admin", "user", "create", "--config", "/etc/gitea/app.ini", "--username", config.getUsername(), "--password", config.getPassword(), "--email", config.getUsername() + "@karavan.space", "--admin"); dockerService.execStart(user.getId(), new LoggerCallback()); LOGGER.info("Created Gitea User"); } catch (Exception e) { LOGGER.error(e.getMessage()); } } }
918
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/docker/DockerServiceUtils.java
/* * 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.docker; import com.github.dockerjava.api.model.*; import io.smallrye.mutiny.tuples.Tuple2; import org.apache.camel.karavan.api.KameletResources; import org.apache.camel.karavan.code.model.DockerComposeHealthCheck; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.apache.camel.karavan.shared.Constants.*; public class DockerServiceUtils { 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<>(); protected ContainerStatus getContainerStatus(Container container, String environment) { String name = container.getNames()[0].replace("/", ""); List<Integer> ports = Arrays.stream(container.getPorts()).map(ContainerPort::getPrivatePort).filter(Objects::nonNull).collect(Collectors.toList()); List<ContainerStatus.Command> commands = getContainerCommand(container.getState()); ContainerStatus.ContainerType type = getContainerType(container.getLabels()); String created = Instant.ofEpochSecond(container.getCreated()).toString(); String projectId = container.getLabels().getOrDefault(LABEL_PROJECT_ID, name); String camelRuntime = container.getLabels().getOrDefault(LABEL_CAMEL_RUNTIME, ""); return ContainerStatus.createWithId(projectId, name, environment, container.getId(), container.getImage(), ports, type, commands, container.getState(), created, camelRuntime); } protected void updateStatistics(ContainerStatus containerStatus, Statistics stats) { if (stats != null && stats.getMemoryStats() != null) { String memoryUsage = formatMemory(stats.getMemoryStats().getUsage()); String memoryLimit = formatMemory(stats.getMemoryStats().getLimit()); containerStatus.setMemoryInfo(memoryUsage + " / " + memoryLimit); containerStatus.setCpuInfo(formatCpu(containerStatus.getContainerName(), stats)); } } protected HealthCheck getHealthCheck(DockerComposeHealthCheck config) { if (config != null) { HealthCheck healthCheck = new HealthCheck().withTest(config.getTest()); if (config.getInterval() != null) { healthCheck.withInterval(durationNanos(config.getInterval())); } if (config.getTimeout() != null) { healthCheck.withTimeout(durationNanos(config.getTimeout())); } if (config.getStart_period() != null) { healthCheck.withStartPeriod(durationNanos(config.getStart_period())); } if (config.getRetries() != null) { healthCheck.withRetries(config.getRetries()); } return healthCheck; } return new HealthCheck(); } protected static String getResourceFile(String path) { try { InputStream inputStream = KameletResources.class.getResourceAsStream(path); return new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); } catch (Exception e) { return null; } } protected static long durationNanos(String s) { if (Pattern.compile("\\d+d\\s").matcher(s).find()) { int idxSpace = s.indexOf(" "); s = "P" + s.substring(0, idxSpace) + "T" + s.substring(idxSpace + 1); } else s = "PT" + s; s = s.replace(" ", ""); return Duration.parse(s).toMillis() * 1000000L; } protected Ports getPortBindings(Map<Integer, Integer> ports) { Ports portBindings = new Ports(); ports.forEach((hostPort, containerPort) -> { Ports.Binding binding = Ports.Binding.bindPort(hostPort); portBindings.bind(ExposedPort.tcp(containerPort), binding); }); return portBindings; } protected String formatMemory(Long memory) { try { if (memory < (1073741824)) { return formatMiB.format(memory.doubleValue() / 1048576) + "MiB"; } else { return formatGiB.format(memory.doubleValue() / 1073741824) + "GiB"; } } catch (Exception e) { return ""; } } protected ContainerStatus.ContainerType getContainerType(Map<String, String> labels) { String type = labels.get(LABEL_TYPE); if (Objects.equals(type, ContainerStatus.ContainerType.devmode.name())) { return ContainerStatus.ContainerType.devmode; } else if (Objects.equals(type, ContainerStatus.ContainerType.devservice.name())) { return ContainerStatus.ContainerType.devservice; } else if (Objects.equals(type, ContainerStatus.ContainerType.project.name())) { return ContainerStatus.ContainerType.project; } else if (Objects.equals(type, ContainerStatus.ContainerType.internal.name())) { return ContainerStatus.ContainerType.internal; } else if (Objects.equals(type, ContainerStatus.ContainerType.build.name())) { return ContainerStatus.ContainerType.build; } return ContainerStatus.ContainerType.unknown; } protected List<ContainerStatus.Command> getContainerCommand(String state) { List<ContainerStatus.Command> result = new ArrayList<>(); if (Objects.equals(state, ContainerStatus.State.created.name())) { result.add(ContainerStatus.Command.run); result.add(ContainerStatus.Command.delete); } else if (Objects.equals(state, ContainerStatus.State.exited.name())) { result.add(ContainerStatus.Command.run); result.add(ContainerStatus.Command.delete); } else if (Objects.equals(state, ContainerStatus.State.running.name())) { result.add(ContainerStatus.Command.pause); result.add(ContainerStatus.Command.stop); result.add(ContainerStatus.Command.delete); } else if (Objects.equals(state, ContainerStatus.State.paused.name())) { result.add(ContainerStatus.Command.run); result.add(ContainerStatus.Command.stop); result.add(ContainerStatus.Command.delete); } else if (Objects.equals(state, ContainerStatus.State.dead.name())) { result.add(ContainerStatus.Command.delete); } return result; } protected String formatCpu(String containerName, Statistics stats) { try { double cpuUsage = 0; long previousCpu = previousStats.containsKey(containerName) ? previousStats.get(containerName).getItem1() : -1; long previousSystem = previousStats.containsKey(containerName) ? previousStats.get(containerName).getItem2() : -1; CpuStatsConfig cpuStats = stats.getCpuStats(); if (cpuStats != null) { CpuUsageConfig cpuUsageConfig = cpuStats.getCpuUsage(); long systemUsage = cpuStats.getSystemCpuUsage(); long totalUsage = cpuUsageConfig.getTotalUsage(); if (previousCpu != -1 && previousSystem != -1) { float cpuDelta = totalUsage - previousCpu; float systemDelta = systemUsage - previousSystem; if (cpuDelta > 0 && systemDelta > 0) { cpuUsage = cpuDelta / systemDelta * cpuStats.getOnlineCpus() * 100; } } previousStats.put(containerName, Tuple2.of(totalUsage, systemUsage)); } return formatCpu.format(cpuUsage) + "%"; } catch (Exception e) { return ""; } } }
919
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code/DockerComposeConverter.java
/* * 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.code; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import org.apache.camel.karavan.code.model.DockerCompose; import org.apache.camel.karavan.code.model.DockerComposeService; 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.Map; public class DockerComposeConverter { private static final String ENVIRONMENT = "environment"; public static DockerCompose fromCode(String code) { Yaml yaml = new Yaml(); Map<String, Object> obj = yaml.load(code); JsonObject json = JsonObject.mapFrom(obj); JsonObject services = json.getJsonObject("services"); JsonObject composeServices = new JsonObject(); services.getMap().forEach((name, value) -> { JsonObject serviceJson = services.getJsonObject(name); DockerComposeService service = convertToDockerComposeService(name, serviceJson); composeServices.put(name, service); }); json.put("services", composeServices); return json.mapTo(DockerCompose.class); } public static DockerComposeService fromCode(String code, String serviceName) { DockerCompose compose = fromCode(code); return compose.getServices().get(serviceName); } public static String toCode(DockerCompose compose) { Yaml yaml = new Yaml(new ComposeRepresenter()); return yaml.dumpAs(compose, Tag.MAP, DumperOptions.FlowStyle.BLOCK); } public static String toCode(DockerComposeService service) { DockerCompose dc = DockerCompose.create(service); return toCode(dc); } private static DockerComposeService convertToDockerComposeService(String name, JsonObject service) { if (service.containsKey(ENVIRONMENT) && service.getValue(ENVIRONMENT) instanceof JsonArray) { JsonObject env = new JsonObject(); service.getJsonArray(ENVIRONMENT).forEach(o -> { String[] kv = o.toString().split("="); env.put(kv[0], kv[1]); }); service.put(ENVIRONMENT, env); } DockerComposeService ds = service.mapTo(DockerComposeService.class); if (ds.getContainer_name() == null) { ds.setContainer_name(name); } return ds; } private static class ComposeRepresenter extends Representer { public ComposeRepresenter() { super(create()); } private static DumperOptions create() { DumperOptions options = new DumperOptions(); options.setExplicitStart(true); options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); options.setLineBreak(DumperOptions.LineBreak.UNIX); return options; } @Override protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { if (propertyValue == null) { return null; } else { NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); Node valueNode = tuple.getValueNode(); if (Tag.NULL.equals(valueNode.getTag())) { return null;// skip 'null' values } if (propertyValue instanceof String && (((String) propertyValue).isEmpty() || ((String) propertyValue).isBlank()) ) { return null;// skip '' values } if (valueNode instanceof CollectionNode) { if (Tag.SEQ.equals(valueNode.getTag())) { SequenceNode seq = (SequenceNode) valueNode; if (seq.getValue().isEmpty()) { return null;// skip empty lists } } if (Tag.MAP.equals(valueNode.getTag())) { MappingNode seq = (MappingNode) valueNode; if (seq.getValue().isEmpty()) { return null;// skip empty maps } } } return tuple; } } } }
920
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code/CodeService.java
/* * 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.code; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.apicurio.datamodels.Library; import io.apicurio.datamodels.models.openapi.OpenApiDocument; import io.quarkus.qute.Engine; import io.quarkus.qute.Template; import io.quarkus.qute.TemplateInstance; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.CamelContext; import org.apache.camel.generator.openapi.RestDslGenerator; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.karavan.api.KameletResources; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.code.model.DockerComposeService; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.git.model.GitRepo; import org.apache.camel.karavan.git.model.GitRepoFile; import org.apache.camel.karavan.infinispan.model.Project; import org.apache.camel.karavan.infinispan.model.ProjectFile; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.service.ConfigService; import org.jboss.logging.Logger; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import java.io.*; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; @ApplicationScoped public class CodeService { private static final Logger LOGGER = Logger.getLogger(CodeService.class.getName()); public static final String APPLICATION_PROPERTIES_FILENAME = "application.properties"; public static final String BUILD_SCRIPT_FILENAME = "build.sh"; public static final String DEV_SERVICES_FILENAME = "devservices.yaml"; public static final String PROJECT_COMPOSE_FILENAME = "docker-compose.yaml"; public static final String PROJECT_JKUBE_EXTENSION = ".jkube.yaml"; public static final String PROJECT_DEPLOYMENT_JKUBE_FILENAME = "deployment" + PROJECT_JKUBE_EXTENSION; private static final String SNIPPETS_PATH = "/snippets/"; private static final int INTERNAL_PORT = 8080; @Inject KubernetesService kubernetesService; @Inject DockerService dockerService; @Inject InfinispanService infinispanService; @Inject Engine engine; @Inject Vertx vertx; List<String> targets = List.of("openshift", "kubernetes", "docker"); List<String> interfaces = List.of("org.apache.camel.AggregationStrategy.java", "org.apache.camel.Processor.java"); public static final Map<String, String> DEFAULT_CONTAINER_RESOURCES = Map.of( "requests.memory", "256Mi", "requests.cpu", "500m", "limits.memory", "2048Mi", "limits.cpu", "2000m" ); public Map<String, String> getProjectFilesForDevMode(String projectId, Boolean withKamelets) { Map<String, String> files = infinispanService.getProjectFiles(projectId).stream() .filter(f -> !Objects.equals(f.getName(), PROJECT_COMPOSE_FILENAME)) .filter(f -> !f.getName().endsWith(PROJECT_JKUBE_EXTENSION)) .collect(Collectors.toMap(ProjectFile::getName, ProjectFile::getCode)); if (withKamelets) { infinispanService.getProjectFiles(Project.Type.kamelets.name()) .forEach(file -> files.put(file.getName(), file.getCode())); } return files; } public ProjectFile getApplicationProperties(Project project) { String target = "docker"; if (ConfigService.inKubernetes()) { target = kubernetesService.isOpenshift() ? "openshift" : "kubernetes"; } String templateName = target + "-" + APPLICATION_PROPERTIES_FILENAME; String templateText = getTemplateText(templateName); Template result = engine.parse(templateText); TemplateInstance instance = result .data("projectId", project.getProjectId()) .data("projectName", project.getName()) .data("projectDescription", project.getDescription()); if (ConfigService.inKubernetes()) { instance.data("namespace", kubernetesService.getNamespace()); } String code = instance.render(); return new ProjectFile(APPLICATION_PROPERTIES_FILENAME, code, project.getProjectId(), Instant.now().toEpochMilli()); } public String saveProjectFilesInTemp(Map<String, String> files) { String temp = vertx.fileSystem().createTempDirectoryBlocking("temp"); files.forEach((fileName, code) -> addFile(temp, fileName, code)); return temp; } private void addFile(String temp, String fileName, String code) { try { String path = temp + File.separator + fileName; vertx.fileSystem().writeFileBlocking(path, Buffer.buffer(code)); } catch (Exception e) { LOGGER.error(e.getMessage()); e.printStackTrace(); } } public String getBuilderScript() { String target = ConfigService.inKubernetes() ? (kubernetesService.isOpenshift() ? "openshift" : "kubernetes") : "docker"; String templateName = target + "-" + BUILD_SCRIPT_FILENAME; return getTemplateText(templateName); } public String getTemplateText(String fileName) { try { List<ProjectFile> files = infinispanService.getProjectFiles(Project.Type.templates.name()); return files.stream().filter(f -> f.getName().equalsIgnoreCase(fileName)) .map(ProjectFile::getCode).findFirst().orElse(null); } catch (Exception e) { LOGGER.error(e.getMessage()); } return null; } public Map<String, String> getTemplates() { Map<String, String> result = new HashMap<>(); List<String> files = new ArrayList<>(interfaces); files.addAll(targets.stream().map(target -> target + "-" + APPLICATION_PROPERTIES_FILENAME).toList()); files.addAll(targets.stream().map(target -> target + "-" + BUILD_SCRIPT_FILENAME).toList()); files.forEach(file -> { String templatePath = SNIPPETS_PATH + file; String templateText = getResourceFile(templatePath); result.put(file, templateText); }); result.put(PROJECT_COMPOSE_FILENAME, getResourceFile(SNIPPETS_PATH + PROJECT_COMPOSE_FILENAME)); return result; } public Map<String, String> getServices() { Map<String, String> result = new HashMap<>(); String templateText = getResourceFile("/services/" + DEV_SERVICES_FILENAME); result.put(DEV_SERVICES_FILENAME, templateText); return result; } public String getResourceFile(String path) { try { InputStream inputStream = KameletResources.class.getResourceAsStream(path); return new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); } catch (Exception e) { return null; } } public String getPropertyValue(String propFileText, String key) { Optional<String> data = propFileText.lines().filter(p -> p.startsWith(key)).findFirst(); return data.map(s -> s.split("=")[1]).orElse(null); } public String generate(String fileName, String openApi, boolean generateRoutes) throws Exception { final ObjectNode node = fileName.endsWith("json") ? readNodeFromJson(openApi) : readNodeFromYaml(openApi); OpenApiDocument document = (OpenApiDocument) Library.readDocument(node); try (CamelContext context = new DefaultCamelContext()) { return RestDslGenerator.toYaml(document).generate(context, generateRoutes); } } private ObjectNode readNodeFromJson(String openApi) throws Exception { final ObjectMapper mapper = new ObjectMapper(); return (ObjectNode) mapper.readTree(openApi); } private ObjectNode readNodeFromYaml(String openApi) throws FileNotFoundException { final ObjectMapper mapper = new ObjectMapper(); Yaml loader = new Yaml(new SafeConstructor(new LoaderOptions())); Map map = loader.load(openApi); return mapper.convertValue(map, ObjectNode.class); } public String getPropertiesFile(GitRepo repo) { try { for (GitRepoFile e : repo.getFiles()){ if (e.getName().equalsIgnoreCase(APPLICATION_PROPERTIES_FILENAME)) { return e.getBody(); } } } catch (Exception e) { } return null; } public static String getProperty(String file, String property) { String prefix = property + "="; return Arrays.stream(file.split(System.lineSeparator())).filter(s -> s.startsWith(prefix)) .findFirst().orElseGet(() -> "") .replace(prefix, ""); } public static String getValueForProperty(String line, String property) { String prefix = property + "="; return line.replace(prefix, ""); } public String getProjectDescription(String file) { String description = getProperty(file, "camel.jbang.project-description"); return description != null && !description.isBlank() ? description : getProperty(file, "camel.karavan.project-description"); } public String getProjectName(String file) { String name = getProperty(file, "camel.jbang.project-name"); return name != null && !name.isBlank() ? name : getProperty(file, "camel.karavan.project-name"); } public ProjectFile createInitialProjectCompose(Project project) { int port = getNextAvailablePort(); String templateText = getTemplateText(PROJECT_COMPOSE_FILENAME); Template result = engine.parse(templateText); TemplateInstance instance = result .data("projectId", project.getProjectId()) .data("projectPort", port) .data("projectImage", project.getProjectId()); String code = instance.render(); return new ProjectFile(PROJECT_COMPOSE_FILENAME, code, project.getProjectId(), Instant.now().toEpochMilli()); } public ProjectFile createInitialDeployment(Project project) { String template = getTemplateText(PROJECT_DEPLOYMENT_JKUBE_FILENAME); return new ProjectFile(PROJECT_DEPLOYMENT_JKUBE_FILENAME, template, project.getProjectId(), Instant.now().toEpochMilli()); } private int getNextAvailablePort() { int dockerPort = dockerService.getMaxPortMapped(INTERNAL_PORT); int projectPort = getMaxPortMappedInProjects(); return Math.max(projectPort, dockerPort) + 1; } private int getMaxPortMappedInProjects() { List<ProjectFile> files = infinispanService.getProjectFilesByName(PROJECT_COMPOSE_FILENAME).stream() .filter(f -> !Objects.equals(f.getProjectId(), Project.Type.templates.name())).toList(); if (!files.isEmpty()) { return files.stream().map(this::getProjectPort) .filter(Objects::nonNull) .mapToInt(Integer::intValue) .max().orElse(INTERNAL_PORT); } else { return INTERNAL_PORT; } } public Integer getProjectPort(ProjectFile composeFile) { DockerComposeService dcs = DockerComposeConverter.fromCode(composeFile.getCode(), composeFile.getProjectId()); Optional<Integer> port = dcs.getPortsMap().entrySet().stream() .filter(e -> Objects.equals(e.getValue(), INTERNAL_PORT)).map(Map.Entry::getKey).findFirst(); return port.orElse(null); } public DockerComposeService getInternalDockerComposeService (String name) { String composeText = getResourceFile("/services/internal.yaml"); return DockerComposeConverter.fromCode(composeText, name); } }
921
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code/model/DockerComposeService.java
/* * 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.code.model; import java.util.*; import java.util.stream.Collectors; public class DockerComposeService { private String container_name; private String image; private String restart; private List<String> ports; private List<String> expose; private List<String> depends_on; private Map<String,String> environment; private DockerComposeHealthCheck healthcheck; public DockerComposeService() { } public String getContainer_name() { return container_name; } public void setContainer_name(String container_name) { this.container_name = container_name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getRestart() { return restart; } public void setRestart(String restart) { this.restart = restart; } public List<String> getPorts() { return ports; } public void setPorts(List<String> ports) { this.ports = ports; } public Map<Integer, Integer> getPortsMap() { Map<Integer, Integer> p = new HashMap<>(); if (ports != null && !ports.isEmpty()) { ports.forEach(s -> { String[] values = s.split(":"); p.put(Integer.parseInt(values[0]), Integer.parseInt(values[1])); }); } return p; } public List<String> getExpose() { return expose; } public void setExpose(List<String> expose) { this.expose = expose; } public List<String> getDepends_on() { return depends_on; } public void setDepends_on(List<String> depends_on) { this.depends_on = depends_on; } public Map<String, String> getEnvironment() { return environment != null ? environment : new HashMap<>(); } public List<String> getEnvironmentList() { return environment != null ? environment.entrySet().stream() .map(e -> e.getKey().concat("=").concat(e.getValue())).collect(Collectors.toList()) : new ArrayList<>(); } public void addEnvironment(String key, String value) { Map<String, String> map = getEnvironment(); map.put(key, value); setEnvironment(map); } public void setEnvironment(Map<String, String> environment) { this.environment = environment; } public DockerComposeHealthCheck getHealthcheck() { return healthcheck; } public void setHealthcheck(DockerComposeHealthCheck healthcheck) { this.healthcheck = healthcheck; } @Override public String toString() { return "DockerComposeService {" + "container_name='" + container_name + '\'' + ", image='" + image + '\'' + ", restart='" + restart + '\'' + ", ports=" + ports + ", expose=" + expose + ", depends_on='" + depends_on + '\'' + ", environment=" + environment + ", healthcheck=" + healthcheck + '}'; } }
922
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code/model/DockerCompose.java
/* * 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.code.model; import java.util.HashMap; import java.util.Map; public class DockerCompose { private Map<String, DockerComposeService> services; public DockerCompose() { } public DockerCompose(Map<String, DockerComposeService> services) { this.services = services; } public static DockerCompose create(DockerComposeService service) { Map<String, DockerComposeService> map = new HashMap<>(); map.put(service.getContainer_name(), service); return new DockerCompose(map); } public Map<String, DockerComposeService> getServices() { return services; } public void setServices(Map<String, DockerComposeService> services) { this.services = services; } }
923
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/code/model/DockerComposeHealthCheck.java
/* * 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.code.model; import java.util.List; public class DockerComposeHealthCheck { private String interval; private Integer retries; private String timeout; private String start_period; private List<String> test; public DockerComposeHealthCheck() { } public String getInterval() { return interval; } public void setInterval(String interval) { this.interval = interval; } public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public List<String> getTest() { return test; } public void setTest(List<String> test) { this.test = test; } public String getStart_period() { return start_period; } public void setStart_period(String start_period) { this.start_period = start_period; } @Override public String toString() { return "HealthCheckConfig{" + "interval='" + interval + '\'' + ", retries=" + retries + ", timeout='" + timeout + '\'' + ", start_period='" + start_period + '\'' + ", test=" + test + '}'; } }
924
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/shared/Property.java
package org.apache.camel.karavan.shared; public enum Property { PROJECT_ID("camel.karavan.project-id=%s"), PROJECT_NAME("camel.karavan.project-name=%s"), PROJECT_DESCRIPTION("camel.karavan.project-description=%s"), GAV("camel.jbang.gav=org.camel.karavan.demo:%s:1"); private final String keyValueFormatter; Property(String keyValueFormatter) { this.keyValueFormatter = keyValueFormatter; } public String getKeyValueFormatter() { return keyValueFormatter; } }
925
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/shared/Configuration.java
/* * 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.shared; import java.util.List; public class Configuration { private String title; private String version; private String infrastructure; private String environment; private List<String> environments; private List<Object> status; public Configuration() { } public Configuration(String title, String version, String infrastructure, String environment, List<String> environments) { this.title = title; this.version = version; this.infrastructure = infrastructure; this.environment = environment; this.environments = environments; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getInfrastructure() { return infrastructure; } public void setInfrastructure(String infrastructure) { this.infrastructure = infrastructure; } public String getEnvironment() { return environment; } public void setEnvironment(String environment) { this.environment = environment; } public List<String> getEnvironments() { return environments; } public void setEnvironments(List<String> environments) { this.environments = environments; } public List<Object> getStatus() { return status; } public void setStatus(List<Object> status) { this.status = status; } }
926
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/shared/Constants.java
/* * 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.shared; public class Constants { public static final String ENV_VAR_JBANG_OPTIONS = "JBANG_OPTIONS"; public static final String LABEL_PART_OF = "app.kubernetes.io/part-of"; public static final String LABEL_TYPE = "org.apache.camel.karavan/type"; public static final String LABEL_PROJECT_ID = "org.apache.camel.karavan/projectId"; public static final String LABEL_CAMEL_RUNTIME = "org.apache.camel.karavan/runtime"; public static final String LABEL_TAG = "org.apache.camel.karavan/tag"; public static final String BUILDER_SUFFIX = "-builder"; public static final String CAMEL_PREFIX = "camel"; public static final String KARAVAN_SECRET_NAME = "karavan"; public static final String KARAVAN_SERVICE_ACCOUNT = "karavan"; public static final String KARAVAN_PREFIX = "karavan"; public static final String JBANG_CACHE_SUFFIX = "jbang-cache"; public static final String M2_CACHE_SUFFIX = "m2-cache"; public static final String PVC_MAVEN_SETTINGS = "maven-settings"; public enum CamelRuntime { CAMEL_MAIN("camel-main"), QUARKUS("quarkus"), SPRING_BOOT("spring-boot"); private final String value; public String getValue() { return value; } CamelRuntime(String value) { this.value = value; } } }
927
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/registry/RegistryConfig.java
/* * 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.registry; public class RegistryConfig { private String registry; private String group; private String username; private String password; public RegistryConfig() { } public RegistryConfig(String registry, String group, String username, String password) { this.registry = registry; this.group = group; this.username = username; this.password = password; } public String getRegistry() { return registry; } public String getGroup() { return group; } public String getUsername() { return username; } public String getPassword() { return password; } }
928
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/registry/RegistryService.java
/* * 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.registry; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.service.ConfigService; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.List; import java.util.Optional; @ApplicationScoped public class RegistryService { private static final Logger LOGGER = Logger.getLogger(RegistryService.class.getName()); @ConfigProperty(name = "karavan.image-registry-install") boolean installRegistry; @ConfigProperty(name = "karavan.image-registry") String registry; @ConfigProperty(name = "karavan.image-group") String group; @ConfigProperty(name = "karavan.image-registry-username") Optional<String> username; @ConfigProperty(name = "karavan.image-registry-password") Optional<String> password; @Inject KubernetesService kubernetesService; public RegistryConfig getRegistryConfig() { String registryUrl = registry; String imageGroup = group; String registryUsername = username.orElse(null); String registryPassword = password.orElse(null); if (ConfigService.inKubernetes()) { registryUrl = kubernetesService.getKaravanSecret("image-registry"); String i = kubernetesService.getKaravanSecret("image-group"); imageGroup = i != null ? i : group; registryUsername = kubernetesService.getKaravanSecret("image-registry-username"); registryPassword = kubernetesService.getKaravanSecret("image-registry-password"); } return new RegistryConfig(registryUrl, imageGroup, registryUsername, registryPassword); } public String getRegistryWithGroupForSync() { String registryUrl = registry; if (!ConfigService.inKubernetes() && installRegistry) { registryUrl = "localhost:5555"; } return registryUrl + "/" + group; } public List<String> getEnvForBuild() { RegistryConfig rc = getRegistryConfig(); List<String> result = new ArrayList<>(); result.add("IMAGE_REGISTRY=" + rc.getRegistry()); if (rc.getUsername() != null && !rc.getUsername().isEmpty()) { result.add("IMAGE_REGISTRY_USERNAME=" + rc.getUsername()); } if (rc.getPassword() != null && !rc.getPassword().isEmpty()) { result.add("IMAGE_REGISTRY_PASSWORD=" + rc.getPassword()); } if (rc.getGroup() != null && !rc.getGroup().isEmpty()) { result.add("IMAGE_GROUP=" + rc.getGroup()); } return result; } }
929
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/StatusResource.java
/* * 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.api; import io.vertx.core.eventbus.EventBus; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.*; import org.jboss.logging.Logger; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import java.util.List; import java.util.Optional; @Path("/api/status") public class StatusResource { private static final Logger LOGGER = Logger.getLogger(StatusResource.class.getName()); @Inject InfinispanService infinispanService; @GET @Produces(MediaType.APPLICATION_JSON) @Path("/deployment/{name}/{env}") public Response getDeploymentStatus(@PathParam("name") String name, @PathParam("env") String env) { DeploymentStatus status = infinispanService.getDeploymentStatus(name, env); if (status != null) { return Response.ok(status).build(); } return Response.noContent().build(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/camel/context") public List<CamelStatus> getCamelContextStatusByEnv() { if (infinispanService.isReady()) { return infinispanService.getCamelStatusesByEnv(CamelStatusValue.Name.context); } else { return List.of(); } } }
930
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectResource.java
/* * 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.api; import jakarta.ws.rs.core.Response; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.*; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.git.GitService; import jakarta.inject.Inject; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import org.apache.camel.karavan.service.ProjectService; import org.apache.camel.karavan.service.ConfigService; import org.jboss.logging.Logger; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Objects; @Path("/api/project") public class ProjectResource { private static final Logger LOGGER = Logger.getLogger(ProjectResource.class.getName()); @Inject InfinispanService infinispanService; @Inject KubernetesService kubernetesService; @Inject DockerService dockerService; @Inject GitService gitService; @Inject ProjectService projectService; @GET @Produces(MediaType.APPLICATION_JSON) public List<Project> getAll(@QueryParam("type") String type) { return projectService.getAllProjects(type); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{project}") public Project get(@PathParam("project") String project) throws Exception { return infinispanService.getProject(project); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Project save(Project project) throws Exception { return projectService.save(project); } @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{project}") public void delete(@HeaderParam("username") String username, @PathParam("project") String project) throws Exception { String projectId = URLDecoder.decode(project, StandardCharsets.UTF_8); gitService.deleteProject(projectId, infinispanService.getProjectFiles(projectId)); infinispanService.getProjectFiles(projectId).forEach(file -> infinispanService.deleteProjectFile(projectId, file.getName())); infinispanService.deleteProject(projectId); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/build/{tag}") public Response build(Project project, @PathParam("tag") String tag) throws Exception { try { projectService.buildProject(project, tag); return Response.ok().entity(project).build(); } catch (Exception e) { LOGGER.error(e.getMessage()); return Response.serverError().entity(e.getMessage()).build(); } } @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/build/{env}/{buildName}") public Response deleteBuild(@HeaderParam("username") String username, @PathParam("env") String env, @PathParam("buildName") String buildName) { buildName = URLDecoder.decode(buildName, StandardCharsets.UTF_8); if (ConfigService.inKubernetes()) { kubernetesService.deletePod(buildName); return Response.ok().build(); } else { dockerService.deleteContainer(buildName); return Response.ok().build(); } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/status/camel/{projectId}/{env}") public Response getCamelStatusForProjectAndEnv(@PathParam("projectId") String projectId, @PathParam("env") String env) { List<CamelStatus> statuses = infinispanService.getCamelStatusesByProjectAndEnv(projectId, env) .stream().map(camelStatus -> { var stats = camelStatus.getStatuses().stream().filter(s -> !Objects.equals(s.getName(), CamelStatusValue.Name.trace)).toList(); camelStatus.setStatuses(stats); return camelStatus; }).toList(); if (statuses != null && !statuses.isEmpty()) { return Response.ok(statuses).build(); } else { return Response.noContent().build(); } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/traces/{projectId}/{env}") public Response getCamelTracesForProjectAndEnv(@PathParam("projectId") String projectId, @PathParam("env") String env) { List<CamelStatus> statuses = infinispanService.getCamelStatusesByProjectAndEnv(projectId, env) .stream().map(camelStatus -> { var stats = camelStatus.getStatuses().stream().filter(s -> Objects.equals(s.getName(), CamelStatusValue.Name.trace)).toList(); camelStatus.setStatuses(stats); return camelStatus; }).toList(); if (statuses != null && !statuses.isEmpty()) { return Response.ok(statuses).build(); } else { return Response.noContent().build(); } } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/copy/{sourceProject}") public Project copy(@PathParam("sourceProject") String sourceProject, Project project) throws Exception { return projectService.copy(sourceProject, project); } }
931
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/InfrastructureResource.java
/* * 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.api; import jakarta.inject.Inject; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.DeploymentStatus; import org.apache.camel.karavan.infinispan.model.ServiceStatus; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.service.ConfigService; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @Path("/api/infrastructure") public class InfrastructureResource { @Inject InfinispanService infinispanService; @Inject KubernetesService kubernetesService; @ConfigProperty(name = "karavan.environment") String environment; private static final Logger LOGGER = Logger.getLogger(InfrastructureResource.class.getName()); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/deployment") public List<DeploymentStatus> getAllDeploymentStatuses() throws Exception { if (infinispanService.isReady()) { return infinispanService.getDeploymentStatuses().stream() .sorted(Comparator.comparing(DeploymentStatus::getProjectId)) .collect(Collectors.toList()); } else { return List.of(); } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/deployment/{env}") public List<DeploymentStatus> getDeploymentStatusesByEnv(@PathParam("env") String env) throws Exception { if (infinispanService.isReady()) { return infinispanService.getDeploymentStatuses(env).stream() .sorted(Comparator.comparing(DeploymentStatus::getProjectId)) .collect(Collectors.toList()); } else { return List.of(); } } @POST @Produces(MediaType.APPLICATION_JSON) @Path("/deployment/rollout/{env}/{name}") public Response rollout(@PathParam("env") String env, @PathParam("name") String name) throws Exception { kubernetesService.rolloutDeployment(name, kubernetesService.getNamespace()); return Response.ok().build(); } @DELETE @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/deployment/{env}/{name}") public Response deleteDeployment(@PathParam("env") String env, @PathParam("name") String name) throws Exception { kubernetesService.deleteDeployment(name, kubernetesService.getNamespace()); return Response.ok().build(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/service") public List<ServiceStatus> getAllServiceStatuses() throws Exception { if (infinispanService.isReady()) { return infinispanService.getServiceStatuses().stream() .sorted(Comparator.comparing(ServiceStatus::getProjectId)) .collect(Collectors.toList()); } else { return List.of(); } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/imagetag/{env}/{projectId}") public Response getProjectImageTags(@PathParam("env") String env, @PathParam("projectId") String projectId) throws Exception { return Response.ok(kubernetesService.getProjectImageTags(projectId, kubernetesService.getNamespace())).build(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/configmaps") public Response getConfigMaps() throws Exception { if (ConfigService.inKubernetes()) { return Response.ok(kubernetesService.getConfigMaps(kubernetesService.getNamespace())).build(); } else { return Response.ok(List.of()).build(); } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/secrets") public Response getSecrets() throws Exception { if (ConfigService.inKubernetes()) { return Response.ok(kubernetesService.getSecrets(kubernetesService.getNamespace())).build(); } else { return Response.ok(List.of()).build(); } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/services") public Response getServices() throws Exception { if (infinispanService.isReady()) { if (ConfigService.inKubernetes()) { return Response.ok(kubernetesService.getServices(kubernetesService.getNamespace())).build(); } else { List<String> list = infinispanService.getContainerStatuses(environment).stream() .map(ci -> ci.getPorts().stream().map(i -> ci.getContainerName() + ":" + i).collect(Collectors.toList())) .flatMap(List::stream).collect(Collectors.toList()); return Response.ok(list).build(); } } else { return Response.ok(List.of()).build(); } } }
932
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/KameletResources.java
/* * 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.api; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.Project; import org.apache.camel.karavan.infinispan.model.ProjectFile; import org.apache.camel.karavan.code.CodeService; import org.yaml.snakeyaml.Yaml; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Path("/api/kamelet") public class KameletResources { @Inject InfinispanService infinispanService; @Inject CodeService codeService; @GET @Produces(MediaType.TEXT_PLAIN) public String getKamelets() { StringBuilder kamelets = new StringBuilder(codeService.getResourceFile("/kamelets/kamelets.yaml")); if (infinispanService.isReady()) { List<ProjectFile> custom = infinispanService.getProjectFiles(Project.Type.kamelets.name()); if (!custom.isEmpty()) { kamelets.append("\n---\n"); kamelets.append(custom.stream() .map(ProjectFile::getCode) .collect(Collectors.joining("\n---\n"))); } } return kamelets.toString(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/names") public List<String> getCustomNames() { if (infinispanService.isReady()) { Yaml yaml = new Yaml(); return infinispanService.getProjectFiles(Project.Type.kamelets.name()).stream() .map(projectFile -> projectFile.getName().replace(".kamelet.yaml", "")) .collect(Collectors.toList()); } else { return List.of(); } } }
933
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectGitResource.java
/* * 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.api; import org.apache.camel.karavan.infinispan.model.Project; import org.apache.camel.karavan.service.ProjectService; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import java.util.HashMap; @Path("/api/git") public class ProjectGitResource { @Inject ProjectService projectService; @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Project push(HashMap<String, String> params) throws Exception { return projectService.commitAndPushProject(params.get("projectId"), params.get("message")); } @GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{projectId}") public Project pull(@PathParam("projectId") String projectId) throws Exception { return projectService.importProject(projectId); } }
934
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/LogWatchResource.java
/* * 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.api; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.LogWatch; import io.smallrye.context.api.ManagedExecutorConfig; import io.smallrye.context.api.NamedInstance; import io.smallrye.mutiny.tuples.Tuple2; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.docker.LogCallback; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.service.ConfigService; import org.eclipse.microprofile.context.ManagedExecutor; import org.jboss.logging.Logger; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.sse.Sse; import jakarta.ws.rs.sse.SseEventSink; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.ConcurrentHashMap; @Path("/api/logwatch") public class LogWatchResource { private static final Logger LOGGER = Logger.getLogger(LogWatchResource.class.getName()); private static final ConcurrentHashMap<String, LogWatch> logWatches = new ConcurrentHashMap<>(); @Inject KubernetesService kubernetesService; @Inject DockerService dockerService; @Inject @ManagedExecutorConfig() @NamedInstance("logExecutor") ManagedExecutor managedExecutor; @GET @Produces(MediaType.SERVER_SENT_EVENTS) @Path("/{type}/{name}") public void eventSourcing(@PathParam("type") String type, @PathParam("name") String name, @Context SecurityContext securityContext, @Context SseEventSink eventSink, @Context Sse sse) { managedExecutor.execute(() -> { LOGGER.info("LogWatch for " + name + " starting..."); if (ConfigService.inKubernetes()) { getKubernetesLogs(name, eventSink, sse); } else { getDockerLogs(type, name, eventSink, sse); } }); } private void getDockerLogs(String type, String name, SseEventSink eventSink, Sse sse) { LOGGER.info("LogCallback for " + name + " starting"); try (SseEventSink sink = eventSink) { LogCallback logCallback = new LogCallback(line -> { if (!sink.isClosed()) { sink.send(sse.newEvent(line)); } }); dockerService.logContainer(name, logCallback); logCallback.close(); sink.close(); LOGGER.info("LogCallback for " + name + " closed"); } catch (Exception e) { LOGGER.error(e.getMessage()); } } private void getKubernetesLogs(String name, SseEventSink eventSink, Sse sse) { try (SseEventSink sink = eventSink) { Tuple2<LogWatch, KubernetesClient> request = kubernetesService.getContainerLogWatch(name); LogWatch logWatch = request.getItem1(); BufferedReader reader = new BufferedReader(new InputStreamReader(logWatch.getOutput())); try { for (String line; (line = reader.readLine()) != null && !sink.isClosed(); ) { sink.send(sse.newEvent(line)); } } catch (IOException e) { LOGGER.error(e.getMessage()); } logWatch.close(); request.getItem2().close(); sink.close(); LOGGER.info("LogWatch for " + name + " closed"); } } }
935
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/ImagesResource.java
/* * 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.api; import io.vertx.core.json.JsonObject; import jakarta.inject.Inject; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.registry.RegistryConfig; import org.apache.camel.karavan.service.ConfigService; import org.apache.camel.karavan.service.ProjectService; import org.apache.camel.karavan.registry.RegistryService; import org.jose4j.base64url.Base64; import java.io.IOException; import java.util.Comparator; import java.util.List; @Path("/api/image") public class ImagesResource { @Inject DockerService dockerService; @Inject RegistryService registryService; @Inject ProjectService projectService; @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{projectId}") public List<String> getImagesForProject(@HeaderParam("username") String username, @PathParam("projectId") String projectId) { RegistryConfig registryConfig = registryService.getRegistryConfig(); String pattern = registryConfig.getGroup() + "/" + projectId; if (ConfigService.inKubernetes()) { return List.of(); } else { return dockerService.getImages() .stream().filter(s -> s.contains(pattern)).sorted(Comparator.reverseOrder()).toList(); } } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{projectId}") public Response build(JsonObject data, @PathParam("projectId") String projectId) throws Exception { try { String imageName = data.getString("imageName"); boolean commit = data.getBoolean("commit"); String message = data.getString("message"); projectService.setProjectImage(projectId, imageName, commit, message); return Response.ok().entity(imageName).build(); } catch (Exception e) { return Response.serverError().entity(e.getMessage()).build(); } } @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{imageName}") public Response deleteImage(@HeaderParam("username") String username, @PathParam("imageName") String imageName) { imageName= new String(Base64.decode(imageName)); if (ConfigService.inKubernetes()) { return Response.ok().build(); } else { dockerService.deleteImage(imageName); return Response.ok().build(); } } }
936
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/DevModeResource.java
/* * 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.api; import io.vertx.core.json.JsonObject; import io.vertx.mutiny.core.eventbus.EventBus; import jakarta.inject.Inject; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.CamelStatus; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.infinispan.model.Project; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.service.CamelService; import org.apache.camel.karavan.service.ProjectService; import org.apache.camel.karavan.service.ConfigService; import org.eclipse.microprofile.config.inject.ConfigProperty; import static org.apache.camel.karavan.service.ContainerStatusService.CONTAINER_STATUS; @Path("/api/devmode") public class DevModeResource { @ConfigProperty(name = "karavan.environment") String environment; @Inject CamelService camelService; @Inject InfinispanService infinispanService; @Inject KubernetesService kubernetesService; @Inject DockerService dockerService; @Inject ProjectService projectService; @Inject EventBus eventBus; @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{jBangOptions}") public Response runProjectWithJBangOptions(Project project, @PathParam("jBangOptions") String jBangOptions) { try { String containerName = projectService.runProjectWithJBangOptions(project, jBangOptions); if (containerName != null) { return Response.ok(containerName).build(); } else { return Response.notModified().build(); } } catch (Exception e) { return Response.serverError().entity(e).build(); } } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response runProject(Project project) throws Exception { return runProjectWithJBangOptions(project, ""); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/reload/{projectId}") public Response reload(@PathParam("projectId") String projectId) { if (infinispanService.isReady()) { camelService.reloadProjectCode(projectId); return Response.ok().build(); } else { return Response.noContent().build(); } } @DELETE @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{projectId}/{deletePVC}") public Response deleteDevMode(@PathParam("projectId") String projectId, @PathParam("deletePVC") boolean deletePVC) { setContainerStatusTransit(projectId, ContainerStatus.ContainerType.devmode.name()); if (ConfigService.inKubernetes()) { kubernetesService.deleteDevModePod(projectId, deletePVC); } else { dockerService.deleteContainer(projectId); } return Response.accepted().build(); } private void setContainerStatusTransit(String name, String type) { ContainerStatus status = infinispanService.getContainerStatus(name, environment, name); if (status == null) { status = ContainerStatus.createByType(name, environment, ContainerStatus.ContainerType.valueOf(type)); } status.setInTransit(true); eventBus.send(CONTAINER_STATUS, JsonObject.mapFrom(status)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/container/{projectId}") public Response getPodStatus(@PathParam("projectId") String projectId) throws RuntimeException { if (infinispanService.isReady()) { ContainerStatus cs = infinispanService.getDevModeContainerStatus(projectId, environment); if (cs != null) { return Response.ok(cs).build(); } else { return Response.noContent().build(); } } else { return Response.noContent().build(); } } }
937
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/ContainerResource.java
/* * 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.api; import io.smallrye.mutiny.Multi; import io.vertx.core.json.JsonObject; import io.vertx.mutiny.core.eventbus.EventBus; import io.vertx.mutiny.core.eventbus.Message; import jakarta.inject.Inject; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.apache.camel.karavan.code.DockerComposeConverter; import org.apache.camel.karavan.code.model.DockerComposeService; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.service.ConfigService; import org.apache.camel.karavan.service.ProjectService; import org.apache.camel.karavan.shared.Constants; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.util.*; import java.util.stream.Collectors; import static org.apache.camel.karavan.service.ContainerStatusService.CONTAINER_STATUS; import static org.apache.camel.karavan.shared.Constants.*; @Path("/api/container") public class ContainerResource { @Inject EventBus eventBus; @Inject InfinispanService infinispanService; @Inject KubernetesService kubernetesService; @Inject DockerService dockerService; @Inject ProjectService projectService; @ConfigProperty(name = "karavan.environment") String environment; private static final Logger LOGGER = Logger.getLogger(ContainerResource.class.getName()); @GET @Produces(MediaType.APPLICATION_JSON) public List<ContainerStatus> getAllContainerStatuses() throws Exception { if (infinispanService.isReady()) { return infinispanService.getContainerStatuses().stream() .sorted(Comparator.comparing(ContainerStatus::getProjectId)) .collect(Collectors.toList()); } else { return List.of(); } } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{env}/{type}/{name}") public Response manageContainer(@PathParam("env") String env, @PathParam("type") String type, @PathParam("name") String name, JsonObject command) throws Exception { if (infinispanService.isReady()) { if (ConfigService.inKubernetes()) { if (command.getString("command").equalsIgnoreCase("delete")) { kubernetesService.deletePod(name); return Response.ok().build(); } } else { // set container statuses setContainerStatusTransit(name, type); // exec docker commands if (command.containsKey("command")) { if (command.getString("command").equalsIgnoreCase("run")) { if (Objects.equals(type, ContainerStatus.ContainerType.devservice.name())) { String code = projectService.getDevServiceCode(); DockerComposeService dockerComposeService = DockerComposeConverter.fromCode(code, name); if (dockerComposeService != null) { Map<String,String> labels = new HashMap<>(); labels.put(LABEL_TYPE, ContainerStatus.ContainerType.devservice.name()); labels.put(LABEL_CAMEL_RUNTIME, Constants.CamelRuntime.CAMEL_MAIN.getValue()); labels.put(LABEL_PROJECT_ID, name); dockerService.createContainerFromCompose(dockerComposeService, labels); dockerService.runContainer(dockerComposeService.getContainer_name()); } } else if (Objects.equals(type, ContainerStatus.ContainerType.project.name())) { DockerComposeService dockerComposeService = projectService.getProjectDockerComposeService(name); if (dockerComposeService != null) { Map<String,String> labels = new HashMap<>(); labels.put(LABEL_TYPE, ContainerStatus.ContainerType.project.name()); labels.put(LABEL_CAMEL_RUNTIME, Constants.CamelRuntime.CAMEL_MAIN.getValue()); labels.put(LABEL_PROJECT_ID, name); dockerService.createContainerFromCompose(dockerComposeService, labels); dockerService.runContainer(dockerComposeService.getContainer_name()); } } else if (Objects.equals(type, ContainerStatus.ContainerType.devmode.name())) { // TODO: merge with DevMode service // dockerForKaravan.createDevmodeContainer(name, ""); // dockerService.runContainer(name); } return Response.ok().build(); } else if (command.getString("command").equalsIgnoreCase("stop")) { dockerService.stopContainer(name); return Response.ok().build(); } else if (command.getString("command").equalsIgnoreCase("pause")) { dockerService.pauseContainer(name); return Response.ok().build(); } else if (command.getString("command").equalsIgnoreCase("delete")) { dockerService.deleteContainer(name); return Response.ok().build(); } } } } return Response.notModified().build(); } private void setContainerStatusTransit(String name, String type){ ContainerStatus status = infinispanService.getContainerStatus(name, environment, name); if (status == null) { status = ContainerStatus.createByType(name, environment, ContainerStatus.ContainerType.valueOf(type)); } status.setInTransit(true); eventBus.send(CONTAINER_STATUS, JsonObject.mapFrom(status)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{env}") public List<ContainerStatus> getContainerStatusesByEnv(@PathParam("env") String env) throws Exception { return infinispanService.getContainerStatuses(env).stream() .sorted(Comparator.comparing(ContainerStatus::getProjectId)) .collect(Collectors.toList()); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{projectId}/{env}") public List<ContainerStatus> getContainerStatusesByProjectAndEnv(@PathParam("projectId") String projectId, @PathParam("env") String env) throws Exception { return infinispanService.getContainerStatuses(projectId, env).stream() .filter(podStatus -> Objects.equals(podStatus.getType(), ContainerStatus.ContainerType.project)) .sorted(Comparator.comparing(ContainerStatus::getContainerName)) .collect(Collectors.toList()); } @DELETE @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{env}/{type}/{name}") public Response deleteContainer(@PathParam("env") String env, @PathParam("type") String type, @PathParam("name") String name) { if (infinispanService.isReady()) { // set container statuses setContainerStatusTransit(name, type); try { if (ConfigService.inKubernetes()) { kubernetesService.deletePod(name); } else { dockerService.deleteContainer(name); } return Response.accepted().build(); } catch (Exception e) { LOGGER.error(e.getMessage()); return Response.notModified().build(); } } return Response.notModified().build(); } // TODO: implement log watch @GET @Path("/log/watch/{env}/{name}") @Produces(MediaType.SERVER_SENT_EVENTS) public Multi<String> getContainerLogWatch(@PathParam("env") String env, @PathParam("name") String name) { LOGGER.info("Start sourcing"); return eventBus.<String>consumer(name + "-" + kubernetesService.getNamespace()).toMulti().map(Message::body); } }
938
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/ProjectFileResource.java
/* * 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.api; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.ProjectFile; import org.apache.camel.karavan.code.CodeService; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.HeaderParam; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @Path("/api/file") public class ProjectFileResource { @Inject InfinispanService infinispanService; @Inject CodeService codeService; @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{projectId}") public List<ProjectFile> get(@HeaderParam("username") String username, @PathParam("projectId") String projectId) throws Exception { return infinispanService.getProjectFiles(projectId).stream() .sorted(Comparator.comparing(ProjectFile::getName)) .collect(Collectors.toList()); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public ProjectFile save(ProjectFile file) throws Exception { file.setLastUpdate(Instant.now().toEpochMilli()); infinispanService.saveProjectFile(file); return file; } @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{project}/{filename}") public void delete(@HeaderParam("username") String username, @PathParam("project") String project, @PathParam("filename") String filename) throws Exception { infinispanService.deleteProjectFile( URLDecoder.decode(project, StandardCharsets.UTF_8.toString()), URLDecoder.decode(filename, StandardCharsets.UTF_8.toString()) ); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/openapi/{generateRest}/{generateRoutes}/{integrationName}") public ProjectFile saveOpenapi(@HeaderParam("username") String username, @PathParam("integrationName") String integrationName, @PathParam("generateRest") boolean generateRest, @PathParam("generateRoutes") boolean generateRoutes, ProjectFile file) throws Exception { infinispanService.saveProjectFile(file); if (generateRest) { String yaml = codeService.generate(file.getName(), file.getCode(), generateRoutes); ProjectFile integration = new ProjectFile(integrationName, yaml, file.getProjectId(), Instant.now().toEpochMilli()); infinispanService.saveProjectFile(integration); return file; } return file; } }
939
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/UsersResource.java
/* * 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.api; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import io.quarkus.oidc.IdToken; import org.eclipse.microprofile.jwt.JsonWebToken; import org.jboss.resteasy.reactive.NoCache; import io.quarkus.security.identity.SecurityIdentity; import java.util.Set; @Path("/api/users") @Produces(MediaType.APPLICATION_JSON) public class UsersResource { @Inject SecurityIdentity securityIdentity; @GET @Path("/me") @NoCache public User me() { return new User(securityIdentity); } public static class User { private final String userName; private final java.util.Set<java.lang.String> roles; User(SecurityIdentity securityIdentity) { this.userName = securityIdentity.getPrincipal().getName(); this.roles = securityIdentity.getRoles(); } public String getUserName() { return userName; } public Set<String> getRoles() { return roles; } } }
940
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/ConfigurationResource.java
/* * 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.api; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.service.ConfigService; @Path("/api/configuration") public class ConfigurationResource { @Inject ConfigService configService; @Inject DockerService dockerService; @GET @Produces(MediaType.APPLICATION_JSON) public Response getConfiguration() throws Exception { return Response.ok(configService.getConfiguration()).build(); } @GET @Path("/info") @Produces(MediaType.APPLICATION_JSON) public Response getInfo() throws Exception { if (ConfigService.inKubernetes()) { return Response.ok().build(); } else { return Response.ok(dockerService.getInfo()).build(); } } }
941
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/ComponentResources.java
/* * 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.api; import org.apache.camel.karavan.code.CodeService; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("/api/component") public class ComponentResources { @Inject CodeService codeService; @GET @Produces(MediaType.APPLICATION_JSON) public String getJson() { return codeService.getResourceFile("/components/components.json"); } }
942
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/api/AuthResource.java
/* * 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.api; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.service.AuthService; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.apache.camel.karavan.service.ProjectService; import org.apache.camel.karavan.shared.Configuration; import org.eclipse.microprofile.health.HealthCheckResponse; import java.util.List; import java.util.Map; import java.util.Objects; @Path("/public") public class AuthResource { @Inject AuthService authService; @Inject ProjectService projectService; @Inject KubernetesService kubernetesService; @Inject InfinispanService infinispanService; @GET @Path("/auth") @Produces(MediaType.TEXT_PLAIN) public Response authType() throws Exception { return Response.ok(authService.authType()).build(); } @GET @Path("/sso-config") @Produces(MediaType.APPLICATION_JSON) public Response ssoConfig() throws Exception { return Response.ok(authService.getSsoConfig()).build(); } @GET @Path("/readiness") @Produces(MediaType.APPLICATION_JSON) public Response getConfiguration() throws Exception { List<HealthCheckResponse> list = List.of( infinispanService.call(), kubernetesService.call(), projectService.call() ); return Response.ok(Map.of( "status", list.stream().allMatch(h -> Objects.equals(h.getStatus(), HealthCheckResponse.Status.UP)), "checks", list )).build(); } }
943
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/InfinispanService.java
/* * 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.infinispan; import jakarta.enterprise.inject.Default; import jakarta.inject.Singleton; import org.apache.camel.karavan.infinispan.model.*; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.faulttolerance.Retry; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.Readiness; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.Search; import org.infinispan.client.hotrod.configuration.ClientIntelligence; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.configuration.StringConfiguration; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.protostream.ProtobufUtil; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.config.Configuration; import org.infinispan.query.dsl.QueryFactory; import org.jboss.logging.Logger; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.infinispan.query.remote.client.ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME; @Default @Readiness @Singleton public class InfinispanService implements HealthCheck { @ConfigProperty(name = "karavan.infinispan.hosts") String infinispanHosts; @ConfigProperty(name = "karavan.infinispan.username") String infinispanUsername; @ConfigProperty(name = "karavan.infinispan.password") String infinispanPassword; private RemoteCache<GroupedKey, Project> projects; private RemoteCache<GroupedKey, ProjectFile> files; private RemoteCache<GroupedKey, DeploymentStatus> deploymentStatuses; private RemoteCache<GroupedKey, ContainerStatus> containerStatuses; private RemoteCache<GroupedKey, Boolean> transits; private RemoteCache<GroupedKey, ServiceStatus> serviceStatuses; private RemoteCache<GroupedKey, CamelStatus> camelStatuses; private final AtomicBoolean ready = new AtomicBoolean(false); private RemoteCacheManager cacheManager; private static final Logger LOGGER = Logger.getLogger(InfinispanService.class.getName()); private static final String DEFAULT_ENVIRONMENT = "dev"; @Retry(maxRetries = 100, delay = 2000) public void tryStart() throws Exception { start(); } void start() throws Exception { LOGGER.info("InfinispanService is starting in remote mode"); Configuration.Builder cfgBuilder = Configuration.builder().setLogOutOfSequenceWrites(false); SerializationContext ctx = ProtobufUtil.newSerializationContext(cfgBuilder.build()); ProtoStreamMarshaller marshaller = new ProtoStreamMarshaller(ctx); marshaller.register(new KaravanSchemaImpl()); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServers(infinispanHosts) .security() .authentication().enable() .username(infinispanUsername) .password(infinispanPassword) .clientIntelligence(ClientIntelligence.BASIC) .marshaller(marshaller); cacheManager = new RemoteCacheManager(builder.build()); if (cacheManager.getConnectionCount() > 0 ) { projects = getOrCreateCache(Project.CACHE); files = getOrCreateCache(ProjectFile.CACHE); containerStatuses = getOrCreateCache(ContainerStatus.CACHE); deploymentStatuses = getOrCreateCache(DeploymentStatus.CACHE); serviceStatuses = getOrCreateCache(ServiceStatus.CACHE); camelStatuses = getOrCreateCache(CamelStatus.CACHE); transits = getOrCreateCache("transits"); deploymentStatuses = getOrCreateCache(DeploymentStatus.CACHE); cacheManager.getCache(PROTOBUF_METADATA_CACHE_NAME).put("karavan.proto", getResourceFile("/proto/karavan.proto")); ready.set(true); LOGGER.info("InfinispanService is started in remote mode"); } else { throw new Exception("Not connected..."); } } private <K, V> RemoteCache<K, V> getOrCreateCache(String name) { String config = getResourceFile("/cache/data-cache-config.xml"); return cacheManager.administration().getOrCreateCache(name, new StringConfiguration(String.format(config, name))); } public boolean isReady() { return ready.get(); } public List<Project> getProjects() { return projects.values().stream().collect(Collectors.toList()); } public void saveProject(Project project) { GroupedKey key = GroupedKey.create(project.getProjectId(), DEFAULT_ENVIRONMENT, project.getProjectId()); projects.put(key, project); projects.put(key, project); } public List<ProjectFile> getProjectFiles(String projectId) { QueryFactory queryFactory = Search.getQueryFactory(files); return queryFactory.<ProjectFile>create("FROM karavan.ProjectFile WHERE projectId = :projectId") .setParameter("projectId", projectId) .execute().list(); } public Map<GroupedKey, ProjectFile> getProjectFilesMap(String projectId) { QueryFactory queryFactory = Search.getQueryFactory(files); return queryFactory.<ProjectFile>create("FROM karavan.ProjectFile WHERE projectId = :projectId") .setParameter("projectId", projectId) .execute().list().stream() .collect(Collectors.toMap(f -> new GroupedKey(f.getProjectId(), DEFAULT_ENVIRONMENT, f.getName()), f -> f)); } public ProjectFile getProjectFile(String projectId, String filename) { QueryFactory queryFactory = Search.getQueryFactory(files); List<ProjectFile> list = queryFactory.<ProjectFile>create("FROM karavan.ProjectFile WHERE name = :name AND projectId = :projectId") .setParameter("name", filename) .setParameter("projectId", projectId) .execute().list(); return !list.isEmpty() ? list.get(0) : null; } public List<ProjectFile> getProjectFilesByName(String filename) { QueryFactory queryFactory = Search.getQueryFactory(files); return queryFactory.<ProjectFile>create("FROM karavan.ProjectFile WHERE name = :name") .setParameter("name", filename) .execute().list(); } public void saveProjectFile(ProjectFile file) { files.put(GroupedKey.create(file.getProjectId(), DEFAULT_ENVIRONMENT, file.getName()), file); } public void saveProjectFiles(Map<GroupedKey, ProjectFile> filesToSave) { long lastUpdate = Instant.now().toEpochMilli(); filesToSave.forEach((groupedKey, projectFile) -> projectFile.setLastUpdate(lastUpdate)); files.putAll(filesToSave); } public void deleteProject(String projectId) { projects.remove(GroupedKey.create(projectId, DEFAULT_ENVIRONMENT, projectId)); } public void deleteProjectFile(String projectId, String filename) { files.remove(GroupedKey.create(projectId, DEFAULT_ENVIRONMENT, filename)); } public Project getProject(String projectId) { return projects.get(GroupedKey.create(projectId, DEFAULT_ENVIRONMENT, projectId)); } public DeploymentStatus getDeploymentStatus(String projectId, String environment) { return deploymentStatuses.get(GroupedKey.create(projectId, environment, projectId)); } public void saveDeploymentStatus(DeploymentStatus status) { deploymentStatuses.put(GroupedKey.create(status.getProjectId(), status.getEnv(), status.getProjectId()), status); } public void deleteDeploymentStatus(DeploymentStatus status) { deploymentStatuses.remove(GroupedKey.create(status.getProjectId(), status.getEnv(), status.getProjectId())); } public List<DeploymentStatus> getDeploymentStatuses() { return new ArrayList<>(deploymentStatuses.values()); } public List<DeploymentStatus> getDeploymentStatuses(String env) { QueryFactory queryFactory = Search.getQueryFactory((RemoteCache<?, ?>) deploymentStatuses); return queryFactory.<DeploymentStatus>create("FROM karavan.DeploymentStatus WHERE env = :env") .setParameter("env", env) .execute().list(); } public void saveServiceStatus(ServiceStatus status) { serviceStatuses.put(GroupedKey.create(status.getProjectId(), status.getEnv(), status.getProjectId()), status); } public void deleteServiceStatus(ServiceStatus status) { serviceStatuses.remove(GroupedKey.create(status.getProjectId(), status.getEnv(), status.getProjectId())); } public List<ServiceStatus> getServiceStatuses() { return new ArrayList<>(serviceStatuses.values()); } public List<Boolean> getTransits() { return new ArrayList<>(transits.values()); } public Boolean getTransit(String projectId, String env, String containerName) { return transits.get(GroupedKey.create(projectId, env, containerName)); } public void setTransit(String projectId, String env, String containerName) { transits.put(GroupedKey.create(projectId, env, containerName), true); } public List<ContainerStatus> getContainerStatuses() { return new ArrayList<>(containerStatuses.values()); } public List<ContainerStatus> getContainerStatuses(String projectId, String env) { QueryFactory queryFactory = Search.getQueryFactory(containerStatuses); return queryFactory.<ContainerStatus>create("FROM karavan.ContainerStatus WHERE projectId = :projectId AND env = :env") .setParameter("projectId", projectId) .setParameter("env", env) .execute().list(); } public ContainerStatus getContainerStatus(String projectId, String env, String containerName) { return containerStatuses.get(GroupedKey.create(projectId, env, containerName)); } public ContainerStatus getDevModeContainerStatus(String projectId, String env) { return containerStatuses.get(GroupedKey.create(projectId, env, projectId)); } public List<ContainerStatus> getContainerStatuses(String env) { QueryFactory queryFactory = Search.getQueryFactory(containerStatuses); return queryFactory.<ContainerStatus>create("FROM karavan.ContainerStatus WHERE env = :env") .setParameter("env", env) .execute().list(); } public List<ContainerStatus> getAllContainerStatuses() { return new ArrayList<>(containerStatuses.values()); } public void saveContainerStatus(ContainerStatus status) { containerStatuses.put(GroupedKey.create(status.getProjectId(), status.getEnv(), status.getContainerName()), status); } public void deleteContainerStatus(ContainerStatus status) { containerStatuses.remove(GroupedKey.create(status.getProjectId(), status.getEnv(), status.getContainerName())); } public void deleteContainerStatus(String projectId, String env, String containerName) { containerStatuses.remove(GroupedKey.create(projectId, env, containerName)); } public CamelStatus getCamelStatus(String projectId, String env, String containerName) { GroupedKey key = GroupedKey.create(projectId, env, containerName); return camelStatuses.get(key); } public CamelStatus getCamelStatus(GroupedKey key) { return camelStatuses.get(key); } public List<CamelStatus> getCamelStatusesByEnv(CamelStatusValue.Name name) { QueryFactory queryFactory = Search.getQueryFactory(camelStatuses); List<CamelStatus> statuses = queryFactory.<CamelStatus>create("FROM karavan.CamelStatus") .execute().list(); return statuses.stream().map(cs -> { var values = cs.getStatuses(); cs.setStatuses(values.stream().filter(v -> Objects.equals(v.getName(), name)).toList()); return cs; }).toList(); } public List<CamelStatus> getCamelStatusesByProjectAndEnv(String projectId, String env) { QueryFactory queryFactory = Search.getQueryFactory(camelStatuses); return queryFactory.<CamelStatus>create("FROM karavan.CamelStatus WHERE projectId = :projectId AND env = :env") .setParameter("projectId", projectId) .setParameter("env", env) .execute().list(); } public void saveCamelStatus(CamelStatus status) { GroupedKey key = GroupedKey.create(status.getProjectId(), status.getEnv(), status.getContainerName()); camelStatuses.put(key, status); } public void deleteCamelStatus(String projectId, String name, String env) { GroupedKey key = GroupedKey.create(projectId, env, name); camelStatuses.remove(key); } public void deleteCamelStatuses(String projectId, String env) { QueryFactory queryFactory = Search.getQueryFactory(camelStatuses); List<CamelStatus> statuses = queryFactory.<CamelStatus>create("FROM karavan.CamelStatus WHERE projectId = :projectId AND env = :env") .setParameter("projectId", projectId) .setParameter("env", env) .execute().list(); statuses.forEach(s -> { GroupedKey key = GroupedKey.create(projectId, env, s.getContainerName()); camelStatuses.remove(key); }); } public List<ContainerStatus> getLoadedDevModeStatuses() { QueryFactory queryFactory = Search.getQueryFactory(containerStatuses); return queryFactory.<ContainerStatus>create("FROM karavan.ContainerStatus WHERE type = :type AND codeLoaded = true") .setParameter("type", ContainerStatus.ContainerType.devmode) .execute().list(); } public List<ContainerStatus> getDevModeStatuses() { QueryFactory queryFactory = Search.getQueryFactory(containerStatuses); return queryFactory.<ContainerStatus>create("FROM karavan.ContainerStatus WHERE type = :type") .setParameter("type", ContainerStatus.ContainerType.devmode) .execute().list(); } public List<ContainerStatus> getContainerStatusByEnv(String env) { QueryFactory queryFactory = Search.getQueryFactory(containerStatuses); return queryFactory.<ContainerStatus>create("FROM karavan.ContainerStatus WHERE env = :env") .setParameter("env", env) .execute().list(); } public void clearAllStatuses() { CompletableFuture.allOf( deploymentStatuses.clearAsync(), containerStatuses.clearAsync(), camelStatuses.clearAsync() ).join(); } private String getResourceFile(String path) { try { InputStream inputStream = InfinispanService.class.getResourceAsStream(path); return new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); } catch (Exception e) { return null; } } @Override public HealthCheckResponse call() { if (isReady()) { return HealthCheckResponse.named("Infinispan").up().build(); } else { return HealthCheckResponse.named("Infinispan").down().build(); } } }
944
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/ProjectFile.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoDoc; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class ProjectFile { public static final String CACHE = "project_files"; @ProtoField(number = 1) String name; @ProtoField(number = 2) String code; @ProtoField(number = 3) @ProtoDoc("@Field(index=Index.YES, analyze = Analyze.YES, store = Store.NO)") String projectId; @ProtoField(number = 4) Long lastUpdate; @ProtoFactory public ProjectFile(String name, String code, String projectId, Long lastUpdate) { this.name = name; this.code = code; this.projectId = projectId; this.lastUpdate = lastUpdate; } public ProjectFile() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public Long getLastUpdate() { return lastUpdate; } public void setLastUpdate(Long lastUpdate) { this.lastUpdate = lastUpdate; } @Override public String toString() { return "ProjectFile{" + "name='" + name + '\'' + ", code='" + code + '\'' + ", projectId='" + projectId + '\'' + ", lastUpdate=" + lastUpdate + '}'; } }
945
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/ContainerStatus.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoEnumValue; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import java.time.Instant; import java.util.ArrayList; import java.util.List; public class ContainerStatus { public enum State { created, running, restarting, paused, exited, dead } public enum ContainerType { @ProtoEnumValue(number = 0, name = "internal") internal, @ProtoEnumValue(number = 1, name = "devmode") devmode, @ProtoEnumValue(number = 2, name = "devservice") devservice, @ProtoEnumValue(number = 4, name = "project") project, @ProtoEnumValue(number = 5, name = "build") build, @ProtoEnumValue(number = 6, name = "unknown") unknown, } public enum Command { @ProtoEnumValue(number = 0, name = "run") run, @ProtoEnumValue(number = 1, name = "pause") pause, @ProtoEnumValue(number = 2, name = "stop") stop, @ProtoEnumValue(number = 3, name = "delete") delete, } public static final String CACHE = "container_statuses"; @ProtoField(number = 1) String projectId; @ProtoField(number = 2) String containerName; @ProtoField(number = 3) String containerId; @ProtoField(number = 4) String image; @ProtoField(number = 5, collectionImplementation = ArrayList.class) List<Integer> ports; @ProtoField(number = 6) String env; @ProtoField(number = 7) ContainerType type; @ProtoField(number = 8) String memoryInfo; @ProtoField(number = 9) String cpuInfo; @ProtoField(number = 10) String created; @ProtoField(number = 11) String finished; @ProtoField(number = 12) List<Command> commands; @ProtoField(number = 13) String state; @ProtoField(number = 14) String phase; @ProtoField(number = 15) Boolean codeLoaded; @ProtoField(number = 16) Boolean inTransit = false; @ProtoField(number = 17) String initDate; @ProtoField(number = 18) String podIP; @ProtoField(number = 19) String camelRuntime; @ProtoFactory public ContainerStatus(String projectId, String containerName, String containerId, String image, List<Integer> ports, String env, ContainerType type, String memoryInfo, String cpuInfo, String created, String finished, List<Command> commands, String state, String phase, Boolean codeLoaded, Boolean inTransit, String initDate, String podIP, String camelRuntime) { this.projectId = projectId; this.containerName = containerName; this.containerId = containerId; this.image = image; this.ports = ports; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.finished = finished; this.commands = commands; this.state = state; this.phase = phase; this.codeLoaded = codeLoaded; this.inTransit = inTransit; this.initDate = initDate; this.podIP = podIP; this.camelRuntime = camelRuntime; } public ContainerStatus(String projectId, String containerName, String containerId, String image, List<Integer> ports, String env, ContainerType type, String memoryInfo, String cpuInfo, String created, String finished, List<Command> commands, String state, String phase, Boolean codeLoaded, Boolean inTransit, String initDate) { this.projectId = projectId; this.containerName = containerName; this.containerId = containerId; this.image = image; this.ports = ports; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.finished = finished; this.commands = commands; this.state = state; this.phase = phase; this.codeLoaded = codeLoaded; this.inTransit = inTransit; this.initDate = initDate; } public ContainerStatus(String projectId, String containerName, String containerId, String image, List<Integer> ports, String env, ContainerType type, String memoryInfo, String cpuInfo, String created, String finished, List<Command> commands, String state, Boolean codeLoaded, Boolean inTransit, String camelRuntime) { this.projectId = projectId; this.containerName = containerName; this.containerId = containerId; this.image = image; this.ports = ports; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.finished = finished; this.commands = commands; this.state = state; this.codeLoaded = codeLoaded; this.camelRuntime = camelRuntime; this.inTransit = inTransit; this.initDate = Instant.now().toString(); } public ContainerStatus(String containerName, List<Command> commands, String projectId, String env, ContainerType type, String memoryInfo, String cpuInfo, String created) { this.containerName = containerName; this.commands = commands; this.projectId = projectId; this.env = env; this.type = type; this.memoryInfo = memoryInfo; this.cpuInfo = cpuInfo; this.created = created; this.initDate = Instant.now().toString(); } public ContainerStatus(String containerName, List<Command> commands, String projectId, String env, ContainerType type, String created) { this.containerName = containerName; this.commands = commands; this.projectId = projectId; this.env = env; this.created = created; this.type = type; this.initDate = Instant.now().toString(); } public static ContainerStatus createDevMode(String projectId, String env) { return new ContainerStatus(projectId, projectId, null, null, null, env, ContainerType.devmode, null, null, null, null, List.of(Command.run), null, false, false, ""); } public static ContainerStatus createByType(String name, String env, ContainerType type) { return new ContainerStatus(name, name, null, null, null, env, type, null, null, null, null, List.of(Command.run), null, false, false, ""); } public static ContainerStatus createWithId(String projectId, String containerName, String env, String containerId, String image, List<Integer> ports, ContainerType type, List<Command> commands, String status, String created, String camelRuntime) { return new ContainerStatus(projectId, containerName, containerId, image, ports, env, type, null, null, created, null, commands, status, false, false, camelRuntime); } public ContainerStatus() { } public String getPodIP() { return podIP; } public void setPodIP(String podIP) { this.podIP = podIP; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getContainerName() { return containerName; } public void setContainerName(String containerName) { this.containerName = containerName; } public String getContainerId() { return containerId; } public void setContainerId(String containerId) { this.containerId = containerId; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public List<Integer> getPorts() { return ports; } public void setPorts(List<Integer> ports) { this.ports = ports; } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } public ContainerType getType() { return type; } public void setType(ContainerType type) { this.type = type; } public String getMemoryInfo() { return memoryInfo; } public void setMemoryInfo(String memoryInfo) { this.memoryInfo = memoryInfo; } public String getCpuInfo() { return cpuInfo; } public void setCpuInfo(String cpuInfo) { this.cpuInfo = cpuInfo; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public List<Command> getCommands() { return commands; } public void setCommands(List<Command> commands) { this.commands = commands; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Boolean getCodeLoaded() { return codeLoaded; } public void setCodeLoaded(Boolean codeLoaded) { this.codeLoaded = codeLoaded; } public Boolean getInTransit() { return inTransit; } public void setInTransit(Boolean inTransit) { this.inTransit = inTransit; } public String getFinished() { return finished; } public void setFinished(String finished) { this.finished = finished; } public String getInitDate() { return initDate; } public void setInitDate(String initDate) { this.initDate = initDate; } public String getPhase() { return phase; } public void setPhase(String phase) { this.phase = phase; } public String getCamelRuntime() { return camelRuntime; } public void setCamelRuntime(String camelRuntime) { this.camelRuntime = camelRuntime; } @Override public String toString() { return "ContainerStatus{" + "projectId='" + projectId + '\'' + ", containerName='" + containerName + '\'' + ", containerId='" + containerId + '\'' + ", image='" + image + '\'' + ", ports=" + ports + ", env='" + env + '\'' + ", type=" + type + ", memoryInfo='" + memoryInfo + '\'' + ", cpuInfo='" + cpuInfo + '\'' + ", created='" + created + '\'' + ", finished='" + finished + '\'' + ", commands=" + commands + ", state='" + state + '\'' + ", phase='" + phase + '\'' + ", codeLoaded=" + codeLoaded + ", inTransit=" + inTransit + ", initDate='" + initDate + '\'' + ", podIP='" + podIP + '\'' + '}'; } }
946
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/KaravanSchema.java
/* * 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.infinispan.model; import org.infinispan.protostream.GeneratedSchema; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; @AutoProtoSchemaBuilder( includeClasses = { GroupedKey.class, Project.class, Project.Type.class, ProjectFile.class, CamelStatus.class, CamelStatusValue.class, CamelStatusValue.Name.class, DeploymentStatus.class, ContainerStatus.class, ContainerStatus.ContainerType.class, ContainerStatus.Command.class, ServiceStatus.class }, schemaFileName = "karavan.proto", schemaFilePath = "proto/", schemaPackageName = "karavan") public interface KaravanSchema extends GeneratedSchema { }
947
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/CamelStatus.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import java.util.ArrayList; import java.util.List; public class CamelStatus { public static final String CACHE = "camel_statuses"; @ProtoField(number = 1) String projectId; @ProtoField(number = 2) String containerName; @ProtoField(number = 3, collectionImplementation = ArrayList.class) List<CamelStatusValue> statuses; @ProtoField(number = 4) String env; @ProtoFactory public CamelStatus(String projectId, String containerName, List<CamelStatusValue> statuses, String env) { this.projectId = projectId; this.containerName = containerName; this.statuses = statuses; this.env = env; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getContainerName() { return containerName; } public void setContainerName(String containerName) { this.containerName = containerName; } public List<CamelStatusValue> getStatuses() { return statuses; } public void setStatuses(List<CamelStatusValue> statuses) { this.statuses = statuses; } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } }
948
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/GroupedKey.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class GroupedKey { @ProtoField(number = 1) String projectId; @ProtoField(number = 2) String env; @ProtoField(number = 3) String key; @ProtoFactory public GroupedKey(String projectId, String env, String key) { this.projectId = projectId; this.env = env; this.key = key; } public static GroupedKey create(String projectId, String env, String key) { return new GroupedKey(projectId, env, key); } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } // @Group https://github.com/quarkusio/quarkus/issues/34677 public String getProjectId() { return projectId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupedKey that = (GroupedKey) o; if (!projectId.equals(that.projectId)) return false; if (!env.equals(that.env)) return false; return key.equals(that.key); } @Override public int hashCode() { int result = projectId.hashCode(); result = 31 * result + env.hashCode(); result = 31 * result + key.hashCode(); return result; } @Override public String toString() { return "GroupedKey{" + "projectId='" + projectId + '\'' + ", env='" + env + '\'' + ", key='" + key + '\'' + '}'; } }
949
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/DeploymentStatus.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class DeploymentStatus { public static final String CACHE = "deployment_statuses"; @ProtoField(number = 1) String projectId; @ProtoField(number = 2) String namespace; @ProtoField(number = 3) String env; @ProtoField(number = 4) String cluster; @ProtoField(number = 5) String image; @ProtoField(number = 6) Integer replicas; @ProtoField(number = 7) Integer readyReplicas; @ProtoField(number = 8) Integer unavailableReplicas; public DeploymentStatus(String projectId, String namespace, String cluster, String env) { this.projectId = projectId; this.namespace = namespace; this.cluster = cluster; this.env = env; this.image = ""; this.replicas = 0; this.readyReplicas = 0; this.unavailableReplicas = 0; } @ProtoFactory public DeploymentStatus(String projectId, String namespace, String cluster, String env, String image, Integer replicas, Integer readyReplicas, Integer unavailableReplicas) { this.projectId = projectId; this.namespace = namespace; this.env = env; this.cluster = cluster; this.image = image; this.replicas = replicas; this.readyReplicas = readyReplicas; this.unavailableReplicas = unavailableReplicas; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Integer getReplicas() { return replicas; } public void setReplicas(Integer replicas) { this.replicas = replicas; } public Integer getReadyReplicas() { return readyReplicas; } public void setReadyReplicas(Integer readyReplicas) { this.readyReplicas = readyReplicas; } public Integer getUnavailableReplicas() { return unavailableReplicas; } public void setUnavailableReplicas(Integer unavailableReplicas) { this.unavailableReplicas = unavailableReplicas; } public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } }
950
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/CamelStatusValue.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoEnumValue; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class CamelStatusValue { public enum Name { @ProtoEnumValue(number = 0, name = "context") context, @ProtoEnumValue (number = 1, name = "inflight") inflight, @ProtoEnumValue (number = 2, name = "memory") memory, @ProtoEnumValue (number = 3, name = "properties") properties, @ProtoEnumValue (number = 4, name = "route") route, @ProtoEnumValue (number = 5, name = "trace") trace, @ProtoEnumValue (number = 6, name = "jvm") jvm, @ProtoEnumValue (number = 7, name = "source") source } @ProtoField(number = 1) Name name; @ProtoField(number = 2) String status; @ProtoFactory public CamelStatusValue(Name name, String status) { this.name = name; this.status = status; } public Name getName() { return name; } public void setName(Name name) { this.name = name; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
951
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/ServiceStatus.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; public class ServiceStatus { public static final String CACHE = "service_statuses"; @ProtoField(number = 1) String projectId; @ProtoField(number = 2) String namespace; @ProtoField(number = 3) String env; @ProtoField(number = 4) String cluster; @ProtoField(number = 5) Integer port; @ProtoField(number = 6) Integer targetPort; @ProtoField(number = 7) String clusterIP; @ProtoField(number = 8) String type; @ProtoFactory public ServiceStatus(String projectId, String namespace, String env, String cluster, Integer port, Integer targetPort, String clusterIP, String type) { this.projectId = projectId; this.namespace = namespace; this.env = env; this.cluster = cluster; this.port = port; this.targetPort = targetPort; this.clusterIP = clusterIP; this.type = type; } public ServiceStatus(String projectId, String namespace, String cluster, String env) { this.projectId = projectId; this.namespace = namespace; this.env = env; this.cluster = cluster; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getEnv() { return env; } public void setEnv(String env) { this.env = env; } public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public Integer getTargetPort() { return targetPort; } public void setTargetPort(Integer targetPort) { this.targetPort = targetPort; } public String getClusterIP() { return clusterIP; } public void setClusterIP(String clusterIP) { this.clusterIP = clusterIP; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
952
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/infinispan/model/Project.java
/* * 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.infinispan.model; import org.infinispan.protostream.annotations.ProtoEnumValue; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import java.time.Instant; public class Project { public static final String CACHE = "projects"; public enum Type { @ProtoEnumValue(number = 0, name = "templates") templates, @ProtoEnumValue (number = 1, name = "kamelets") kamelets, @ProtoEnumValue (number = 2, name = "services") services, @ProtoEnumValue (number = 3, name = "normal") normal, } @ProtoField(number = 1) String projectId; @ProtoField(number = 2) String name; @ProtoField(number = 3) String description; @ProtoField(number = 4) String lastCommit; @ProtoField(number = 5) Long lastCommitTimestamp; @ProtoField(number = 6) Type type; @ProtoFactory public Project(String projectId, String name, String description, String lastCommit, Long lastCommitTimestamp, Type type) { this.projectId = projectId; this.name = name; this.description = description; this.lastCommit = lastCommit; this.lastCommitTimestamp = lastCommitTimestamp; this.type = type; } public Project(String projectId, String name, String description, String lastCommit, Long lastCommitTimestamp) { this.projectId = projectId; this.name = name; this.description = description; this.lastCommit = lastCommit; this.lastCommitTimestamp = lastCommitTimestamp; this.type = Type.normal; } public Project(String projectId, String name, String description) { this.projectId = projectId; this.name = name; this.description = description; this.lastCommitTimestamp = Instant.now().toEpochMilli(); this.type = Type.normal; } public Project() { this.type = Type.normal; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLastCommit() { return lastCommit; } public void setLastCommit(String lastCommit) { this.lastCommit = lastCommit; } public Long getLastCommitTimestamp() { return lastCommitTimestamp; } public void setLastCommitTimestamp(Long lastCommitTimestamp) { this.lastCommitTimestamp = lastCommitTimestamp; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } }
953
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/service/KaravanService.java
/* * 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.quarkus.runtime.Quarkus; import io.quarkus.runtime.ShutdownEvent; import io.quarkus.runtime.Startup; import io.quarkus.runtime.StartupEvent; import io.quarkus.vertx.ConsumeEvent; import io.vertx.core.eventbus.EventBus; import jakarta.inject.Singleton; import org.apache.camel.karavan.docker.DockerForGitea; import org.apache.camel.karavan.docker.DockerForInfinispan; import org.apache.camel.karavan.docker.DockerForRegistry; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.git.GiteaService; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.Liveness; import org.jboss.logging.Logger; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import java.io.IOException; @Startup @Liveness @Singleton public class KaravanService implements HealthCheck { private static final Logger LOGGER = Logger.getLogger(KaravanService.class.getName()); @ConfigProperty(name = "karavan.git-install-gitea") boolean giteaInstall; @ConfigProperty(name = "karavan.image-registry-install") boolean registryInstall; @Inject KubernetesService kubernetesService; @Inject DockerService dockerService; @Inject DockerForGitea dockerForGitea; @Inject DockerForRegistry dockerForRegistry; @Inject DockerForInfinispan dockerForInfinispan; @Inject InfinispanService infinispanService; @Inject EventBus eventBus; @Inject GiteaService giteaService; @Inject ProjectService projectService; private static final String START_KUBERNETES_SERVICES = "START_KUBERNETES_LISTENERS"; private static final String START_INTERNAL_DOCKER_SERVICES = "START_INTERNAL_DOCKER_SERVICES"; private static final String START_SERVICES = "START_SERVICES"; @Override public HealthCheckResponse call() { return HealthCheckResponse.up("Karavan"); } void onStart(@Observes StartupEvent ev) throws Exception { if (!ConfigService.inKubernetes()) { eventBus.publish(START_INTERNAL_DOCKER_SERVICES, null); } else { eventBus.publish(START_KUBERNETES_SERVICES, null); } eventBus.publish(START_SERVICES, null); } @ConsumeEvent(value = START_INTERNAL_DOCKER_SERVICES, blocking = true) void startInternalDockerServices(String data) throws Exception { LOGGER.info("Starting Karavan in Docker"); if (!dockerService.checkDocker()){ Quarkus.asyncExit(); } else { dockerService.createNetwork(); dockerService.startListeners(); dockerForInfinispan.startInfinispan(); if (giteaInstall) { dockerForGitea.startGitea(); giteaService.install(); dockerForGitea.createGiteaUser(); giteaService.createRepository(); } if (registryInstall) { dockerForRegistry.startRegistry(); } } } @ConsumeEvent(value = START_KUBERNETES_SERVICES, blocking = true) void startKubernetesServices(String data) throws Exception { LOGGER.info("Starting Karavan in Kubernetes"); if (giteaInstall) { giteaService.createRepository(); } kubernetesService.startInformers(null); } @ConsumeEvent(value = START_SERVICES, blocking = true) void startServices(String data) throws Exception { infinispanService.tryStart(); projectService.tryStart(); } void onStop(@Observes ShutdownEvent ev) throws IOException { LOGGER.info("Stop Listeners"); if (ConfigService.inKubernetes()) { kubernetesService.stopInformers(); } else { dockerService.stopListeners(); } LOGGER.info("Stop Karavan"); } }
954
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/service/CamelService.java
/* * 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.quarkus.scheduler.Scheduled; import io.quarkus.vertx.ConsumeEvent; import io.vertx.core.json.JsonObject; import io.vertx.mutiny.core.Vertx; import io.vertx.mutiny.core.buffer.Buffer; import io.vertx.mutiny.core.eventbus.EventBus; import io.vertx.mutiny.ext.web.client.HttpResponse; import io.vertx.mutiny.ext.web.client.WebClient; import org.apache.camel.karavan.code.CodeService; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.CamelStatus; import org.apache.camel.karavan.infinispan.model.CamelStatusValue; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.shared.Constants; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.faulttolerance.CircuitBreaker; import org.jboss.logging.Logger; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.*; import java.util.concurrent.ExecutionException; @ApplicationScoped public class CamelService { private static final Logger LOGGER = Logger.getLogger(CamelService.class.getName()); public static final String CMD_COLLECT_CAMEL_STATUS = "collect-camel-status"; public static final String RELOAD_PROJECT_CODE = "RELOAD_PROJECT_CODE"; @Inject InfinispanService infinispanService; @Inject CodeService codeService; @Inject KubernetesService kubernetesService; @Inject ProjectService projectService; @ConfigProperty(name = "karavan.environment") String environment; @Inject Vertx vertx; @Inject EventBus eventBus; WebClient webClient; public WebClient getWebClient() { if (webClient == null) { webClient = WebClient.create(vertx); } return webClient; } @Scheduled(every = "{karavan.camel.status.interval}", concurrentExecution = Scheduled.ConcurrentExecution.SKIP) public void collectCamelStatuses() { if (infinispanService.isReady()) { infinispanService.getContainerStatuses(environment).stream() .filter(cs -> cs.getType() == ContainerStatus.ContainerType.project || cs.getType() == ContainerStatus.ContainerType.devmode ).filter(cs -> Objects.equals(cs.getCamelRuntime(), Constants.CamelRuntime.CAMEL_MAIN.getValue())) .forEach(cs -> { CamelStatusRequest csr = new CamelStatusRequest(cs.getProjectId(), cs.getContainerName()); eventBus.publish(CMD_COLLECT_CAMEL_STATUS, JsonObject.mapFrom(Map.of("containerStatus", cs, "camelStatusRequest", csr)) ); }); } } @ConsumeEvent(value = RELOAD_PROJECT_CODE, blocking = true, ordered = true) public void reloadProjectCode(String projectId) { LOGGER.info("Reload project code " + projectId); try { Map<String, String> files = codeService.getProjectFilesForDevMode(projectId, true); files.forEach((name, code) -> putRequest(projectId, name, code, 1000)); reloadRequest(projectId); ContainerStatus containerStatus = infinispanService.getDevModeContainerStatus(projectId, environment); containerStatus.setCodeLoaded(true); eventBus.send(ContainerStatusService.CONTAINER_STATUS, JsonObject.mapFrom(containerStatus)); } catch (Exception ex) { LOGGER.error(ex.getMessage()); } } @CircuitBreaker(requestVolumeThreshold = 10, failureRatio = 0.5, delay = 1000) public boolean putRequest(String containerName, String fileName, String body, int timeout) { try { String url = getContainerAddressForReload(containerName) + "/q/upload/" + fileName; HttpResponse<Buffer> result = getWebClient().putAbs(url) .timeout(timeout).sendBuffer(Buffer.buffer(body)).subscribeAsCompletionStage().toCompletableFuture().get(); return result.statusCode() == 200; } catch (Exception e) { LOGGER.info(e.getMessage()); } return false; } public String reloadRequest(String containerName) { String url = getContainerAddressForReload(containerName) + "/q/dev/reload?reload=true"; try { return result(url, 1000); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage()); } return null; } public String getContainerAddressForReload(String containerName) { if (ConfigService.inKubernetes()) { return "http://" + containerName + "." + kubernetesService.getNamespace(); } else if (ConfigService.inDocker()) { return "http://" + containerName + ":8080"; } else { Integer port = projectService.getProjectPort(containerName); return "http://localhost:" + port; } } public String getContainerAddressForStatus(ContainerStatus containerStatus) { if (ConfigService.inKubernetes()) { String podIP = containerStatus.getPodIP().replace(".", "-"); return "http://" + podIP + "." + kubernetesService.getNamespace() + ".pod.cluster.local:8080"; } else if (ConfigService.inDocker()) { return "http://" + containerStatus.getContainerName() + ":8080"; } else { Integer port = projectService.getProjectPort(containerStatus.getContainerName()); return "http://localhost:" + port; } } public String getCamelStatus(ContainerStatus containerStatus, CamelStatusValue.Name statusName) { String url = getContainerAddressForStatus(containerStatus) + "/q/dev/" + statusName.name(); try { return result(url, 500); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage()); } return null; } @ConsumeEvent(value = CMD_COLLECT_CAMEL_STATUS, blocking = true, ordered = true) public void collectCamelStatuses(JsonObject data) { CamelStatusRequest dms = data.getJsonObject("camelStatusRequest").mapTo(CamelStatusRequest.class); ContainerStatus containerStatus = data.getJsonObject("containerStatus").mapTo(ContainerStatus.class); String projectId = dms.getProjectId(); String containerName = dms.getContainerName(); List<CamelStatusValue> statuses = new ArrayList<>(); Arrays.stream(CamelStatusValue.Name.values()).forEach(statusName -> { String status = getCamelStatus(containerStatus, statusName); if (status != null) { statuses.add(new CamelStatusValue(statusName, status)); if (ConfigService.inKubernetes() && Objects.equals(statusName, CamelStatusValue.Name.context)) { checkReloadRequired(containerStatus); } } }); CamelStatus cs = new CamelStatus(projectId, containerName, statuses, environment); infinispanService.saveCamelStatus(cs); } private void checkReloadRequired(ContainerStatus cs) { if (ConfigService.inKubernetes()) { if (!Objects.equals(cs.getCodeLoaded(), true) && Objects.equals(cs.getState(), ContainerStatus.State.running.name()) && Objects.equals(cs.getType(), ContainerStatus.ContainerType.devmode)) { eventBus.publish(RELOAD_PROJECT_CODE, cs.getProjectId()); } } } @CircuitBreaker(requestVolumeThreshold = 10, failureRatio = 0.5, delay = 1000) public String result(String url, int timeout) throws InterruptedException, ExecutionException { try { HttpResponse<Buffer> result = getWebClient().getAbs(url).putHeader("Accept", "application/json") .timeout(timeout).send().subscribeAsCompletionStage().toCompletableFuture().get(); if (result.statusCode() == 200) { JsonObject res = result.bodyAsJsonObject(); return res.encodePrettily(); } } catch (Exception e) { LOGGER.info(e.getMessage()); } return null; } public static class CamelStatusRequest { private String projectId; private String containerName; public CamelStatusRequest() { } public CamelStatusRequest(String projectId, String containerName) { this.projectId = projectId; this.containerName = containerName; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getContainerName() { return containerName; } public void setContainerName(String containerName) { this.containerName = containerName; } } }
955
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/service/ProjectService.java
/* * 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.JsonObject; import io.vertx.mutiny.core.eventbus.EventBus; import org.apache.camel.karavan.code.CodeService; import org.apache.camel.karavan.code.DockerComposeConverter; import org.apache.camel.karavan.docker.DockerForKaravan; import org.apache.camel.karavan.code.model.DockerComposeService; import org.apache.camel.karavan.git.GitService; import org.apache.camel.karavan.git.model.GitRepo; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.*; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.registry.RegistryService; import org.apache.camel.karavan.shared.Property; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.Readiness; import org.jboss.logging.Logger; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Default; import jakarta.inject.Inject; import java.time.Instant; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.apache.camel.karavan.code.CodeService.*; @Default @Readiness @ApplicationScoped public class ProjectService implements HealthCheck { private static final Logger LOGGER = Logger.getLogger(ProjectService.class.getName()); @ConfigProperty(name = "karavan.environment") String environment; @Inject InfinispanService infinispanService; @Inject KubernetesService kubernetesService; @Inject DockerForKaravan dockerForKaravan; @Inject RegistryService registryService; @Inject GitService gitService; @Inject CodeService codeService; @Inject EventBus eventBus; private AtomicBoolean ready = new AtomicBoolean(false); @Override public HealthCheckResponse call() { if (ready.get()) { return HealthCheckResponse.named("Projects").up().build(); } else { return HealthCheckResponse.named("Projects").down().build(); } } public String runProjectWithJBangOptions(Project project, String jBangOptions) throws Exception { String containerName = project.getProjectId(); ContainerStatus status = infinispanService.getDevModeContainerStatus(project.getProjectId(), environment); if (status == null) { status = ContainerStatus.createDevMode(project.getProjectId(), environment); } if (!Objects.equals(status.getState(), ContainerStatus.State.running.name())) { status.setInTransit(true); eventBus.send(ContainerStatusService.CONTAINER_STATUS, JsonObject.mapFrom(status)); if (ConfigService.inKubernetes()) { kubernetesService.runDevModeContainer(project, jBangOptions); } else { Map<String, String> files = codeService.getProjectFilesForDevMode(project.getProjectId(), true); ProjectFile compose = infinispanService.getProjectFile(project.getProjectId(), PROJECT_COMPOSE_FILENAME); DockerComposeService dcs = DockerComposeConverter.fromCode(compose.getCode(), project.getProjectId()); dockerForKaravan.runProjectInDevMode(project.getProjectId(), jBangOptions, dcs.getPortsMap(), files); } return containerName; } else { return null; } } public void buildProject(Project project, String tag) throws Exception { tag = tag != null && !tag.isEmpty() && !tag.isBlank() ? tag : Instant.now().toString().substring(0, 19).replace(":", "-"); String script = codeService.getBuilderScript(); List<String> env = getProjectEnvForBuild(project, tag); if (ConfigService.inKubernetes()) { kubernetesService.runBuildProject(project, script, env, tag); } else { env.addAll(getConnectionsEnvForBuild()); dockerForKaravan.runBuildProject(project, script, env, tag); } } private List<String> getProjectEnvForBuild(Project project, String tag) { return new ArrayList<>(List.of( "PROJECT_ID=" + project.getProjectId(), "TAG=" + tag )); } private List<String> getConnectionsEnvForBuild() { List<String> env = new ArrayList<>(); env.addAll(registryService.getEnvForBuild()); env.addAll(gitService.getEnvForBuild()); return env; } public List<Project> getAllProjects(String type) { if (infinispanService.isReady()) { List<ProjectFile> files = infinispanService.getProjectFilesByName(PROJECT_COMPOSE_FILENAME); return infinispanService.getProjects().stream() .filter(p -> type == null || Objects.equals(p.getType().name(), type)) .sorted(Comparator.comparing(Project::getProjectId)) .collect(Collectors.toList()); } else { return List.of(); } } private String getImage(List<ProjectFile> files, String projectId) { Optional<ProjectFile> file = files.stream().filter(f -> Objects.equals(f.getProjectId(), projectId)).findFirst(); if (file.isPresent()) { DockerComposeService service = DockerComposeConverter.fromCode(file.get().getCode(), projectId); String image = service.getImage(); return Objects.equals(image, projectId) ? null : image; } else { return null; } } public Project save(Project project) throws Exception { boolean isNew = infinispanService.getProject(project.getProjectId()) == null; infinispanService.saveProject(project); if (isNew) { ProjectFile appProp = codeService.getApplicationProperties(project); infinispanService.saveProjectFile(appProp); if (!ConfigService.inKubernetes()) { ProjectFile projectCompose = codeService.createInitialProjectCompose(project); infinispanService.saveProjectFile(projectCompose); } else if (kubernetesService.isOpenshift()){ ProjectFile projectCompose = codeService.createInitialDeployment(project); infinispanService.saveProjectFile(projectCompose); } } return project; } public Project copy(String sourceProjectId, Project project) throws Exception { Project sourceProject = infinispanService.getProject(sourceProjectId); // Save project infinispanService.saveProject(project); // Copy files from the source and make necessary modifications Map<GroupedKey, ProjectFile> filesMap = infinispanService.getProjectFilesMap(sourceProjectId).entrySet().stream() .filter(e -> !Objects.equals(e.getValue().getName(), PROJECT_COMPOSE_FILENAME) && !Objects.equals(e.getValue().getName(), PROJECT_DEPLOYMENT_JKUBE_FILENAME) ) .collect(Collectors.toMap( e -> new GroupedKey(project.getProjectId(), e.getKey().getEnv(), e.getKey().getKey()), e -> { ProjectFile file = e.getValue(); file.setProjectId(project.getProjectId()); if(Objects.equals(file.getName(), APPLICATION_PROPERTIES_FILENAME)) { modifyPropertyFileOnProjectCopy(file, sourceProject, project); } return file; }) ); infinispanService.saveProjectFiles(filesMap); if (!ConfigService.inKubernetes()) { ProjectFile projectCompose = codeService.createInitialProjectCompose(project); infinispanService.saveProjectFile(projectCompose); } else if (kubernetesService.isOpenshift()){ ProjectFile projectCompose = codeService.createInitialDeployment(project); infinispanService.saveProjectFile(projectCompose); } return project; } private void modifyPropertyFileOnProjectCopy(ProjectFile propertyFile, Project sourceProject, Project project) { String fileContent = propertyFile.getCode(); String sourceProjectIdProperty = String.format(Property.PROJECT_ID.getKeyValueFormatter(), sourceProject.getProjectId()); String sourceProjectNameProperty = String.format(Property.PROJECT_NAME.getKeyValueFormatter(), sourceProject.getName()); String sourceProjectDescriptionProperty = String.format(Property.PROJECT_DESCRIPTION.getKeyValueFormatter(), sourceProject.getDescription()); String sourceGavProperty = String.format(Property.GAV.getKeyValueFormatter(), sourceProject.getProjectId()); String[] searchValues = {sourceProjectIdProperty, sourceProjectNameProperty, sourceProjectDescriptionProperty, sourceGavProperty}; String updatedProjectIdProperty = String.format(Property.PROJECT_ID.getKeyValueFormatter(), project.getProjectId()); String updatedProjectNameProperty = String.format(Property.PROJECT_NAME.getKeyValueFormatter(), project.getName()); String updatedProjectDescriptionProperty = String.format(Property.PROJECT_DESCRIPTION.getKeyValueFormatter(), project.getDescription()); String updatedGavProperty = String.format(Property.GAV.getKeyValueFormatter(), project.getProjectId()); String[] replacementValues = {updatedProjectIdProperty, updatedProjectNameProperty, updatedProjectDescriptionProperty, updatedGavProperty}; String updatedCode = StringUtils.replaceEach(fileContent, searchValues, replacementValues); propertyFile.setCode(updatedCode); } public Integer getProjectPort(String projectId) { ProjectFile composeFile = infinispanService.getProjectFile(projectId, PROJECT_COMPOSE_FILENAME); return codeService.getProjectPort(composeFile); } // @Retry(maxRetries = 100, delay = 2000) public void tryStart() throws Exception { if (infinispanService.isReady() && gitService.checkGit()) { if (infinispanService.getProjects().isEmpty()) { importAllProjects(); } addKameletsProject(); addTemplatesProject(); addServicesProject(); ready.set(true); } else { LOGGER.info("Projects are not ready"); throw new Exception("Projects are not ready"); } } private void importAllProjects() { LOGGER.info("Import projects from Git"); try { List<GitRepo> repos = gitService.readProjectsToImport(); repos.forEach(repo -> { Project project; String folderName = repo.getName(); if (folderName.equals(Project.Type.templates.name())) { project = new Project(Project.Type.templates.name(), "Templates", "Templates", repo.getCommitId(), repo.getLastCommitTimestamp(), Project.Type.templates); } else if (folderName.equals(Project.Type.kamelets.name())) { project = new Project(Project.Type.kamelets.name(), "Custom Kamelets", "Custom Kamelets", repo.getCommitId(), repo.getLastCommitTimestamp(), Project.Type.kamelets); } else if (folderName.equals(Project.Type.services.name())) { project = new Project(Project.Type.services.name(), "Services", "Development Services", repo.getCommitId(), repo.getLastCommitTimestamp(), Project.Type.services); } else { project = getProjectFromRepo(repo); } infinispanService.saveProject(project); repo.getFiles().forEach(repoFile -> { ProjectFile file = new ProjectFile(repoFile.getName(), repoFile.getBody(), folderName, repoFile.getLastCommitTimestamp()); infinispanService.saveProjectFile(file); }); }); } catch (Exception e) { LOGGER.error("Error during project import", e); } } public Project importProject(String projectId) { LOGGER.info("Import project from Git " + projectId); try { GitRepo repo = gitService.readProjectFromRepository(projectId); return importProjectFromRepo(repo); } catch (Exception e) { LOGGER.error("Error during project import", e); return null; } } private Project importProjectFromRepo(GitRepo repo) { LOGGER.info("Import project from GitRepo " + repo.getName()); try { Project project = getProjectFromRepo(repo); infinispanService.saveProject(project); repo.getFiles().forEach(repoFile -> { ProjectFile file = new ProjectFile(repoFile.getName(), repoFile.getBody(), repo.getName(), repoFile.getLastCommitTimestamp()); infinispanService.saveProjectFile(file); }); return project; } catch (Exception e) { LOGGER.error("Error during project import", e); return null; } } public Project getProjectFromRepo(GitRepo repo) { String folderName = repo.getName(); String propertiesFile = codeService.getPropertiesFile(repo); String projectName = codeService.getProjectName(propertiesFile); String projectDescription = codeService.getProjectDescription(propertiesFile); return new Project(folderName, projectName, projectDescription, repo.getCommitId(), repo.getLastCommitTimestamp()); } public Project commitAndPushProject(String projectId, String message) throws Exception { Project p = infinispanService.getProject(projectId); List<ProjectFile> files = infinispanService.getProjectFiles(projectId); RevCommit commit = gitService.commitAndPushProject(p, files, message); String commitId = commit.getId().getName(); Long lastUpdate = commit.getCommitTime() * 1000L; p.setLastCommit(commitId); p.setLastCommitTimestamp(lastUpdate); infinispanService.saveProject(p); return p; } void addKameletsProject() { LOGGER.info("Add custom kamelets project if not exists"); try { Project kamelets = infinispanService.getProject(Project.Type.kamelets.name()); if (kamelets == null) { kamelets = new Project(Project.Type.kamelets.name(), "Custom Kamelets", "Custom Kamelets", "", Instant.now().toEpochMilli(), Project.Type.kamelets); infinispanService.saveProject(kamelets); commitAndPushProject(Project.Type.kamelets.name(), "Add custom kamelets"); } } catch (Exception e) { LOGGER.error("Error during custom kamelets project creation", e); } } void addTemplatesProject() { LOGGER.info("Add templates project if not exists"); try { Project templates = infinispanService.getProject(Project.Type.templates.name()); if (templates == null) { templates = new Project(Project.Type.templates.name(), "Templates", "Templates", "", Instant.now().toEpochMilli(), Project.Type.templates); infinispanService.saveProject(templates); codeService.getTemplates().forEach((name, value) -> { ProjectFile file = new ProjectFile(name, value, Project.Type.templates.name(), Instant.now().toEpochMilli()); infinispanService.saveProjectFile(file); }); commitAndPushProject(Project.Type.templates.name(), "Add default templates"); } } catch (Exception e) { LOGGER.error("Error during templates project creation", e); } } void addServicesProject() { LOGGER.info("Add services project if not exists"); try { Project services = infinispanService.getProject(Project.Type.services.name()); if (services == null) { services = new Project(Project.Type.services.name(), "Services", "Development Services", "", Instant.now().toEpochMilli(), Project.Type.services); infinispanService.saveProject(services); codeService.getServices().forEach((name, value) -> { ProjectFile file = new ProjectFile(name, value, Project.Type.services.name(), Instant.now().toEpochMilli()); infinispanService.saveProjectFile(file); }); commitAndPushProject(Project.Type.services.name(), "Add services"); } } catch (Exception e) { LOGGER.error("Error during services project creation", e); } } public String getDevServiceCode() { List<ProjectFile> files = infinispanService.getProjectFiles(Project.Type.services.name()); Optional<ProjectFile> file = files.stream().filter(f -> f.getName().equals(DEV_SERVICES_FILENAME)).findFirst(); return file.orElse(new ProjectFile()).getCode(); } public void setProjectImage(String projectId, String imageName, boolean commit, String message) throws Exception { ProjectFile file = infinispanService.getProjectFile(projectId, PROJECT_COMPOSE_FILENAME); if (file != null) { DockerComposeService service = DockerComposeConverter.fromCode(file.getCode(), projectId); service.setImage(imageName); String code = DockerComposeConverter.toCode(service); file.setCode(code); infinispanService.saveProjectFile(file); if (commit) { commitAndPushProject(projectId, message); } } } public DockerComposeService getProjectDockerComposeService(String projectId) { ProjectFile file = infinispanService.getProjectFile(projectId, PROJECT_COMPOSE_FILENAME); if (file != null) { return DockerComposeConverter.fromCode(file.getCode(), projectId); } return null; } }
956
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/service/ContainerStatusService.java
/* * 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.quarkus.scheduler.Scheduled; import io.quarkus.vertx.ConsumeEvent; import io.vertx.core.eventbus.EventBus; import io.vertx.core.json.JsonObject; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.apache.camel.karavan.docker.DockerService; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.infinispan.model.Project; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.jboss.logging.Logger; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Objects; @ApplicationScoped public class ContainerStatusService { public static final String CONTAINER_STATUS = "CONTAINER_STATUS"; private static final Logger LOGGER = Logger.getLogger(ContainerStatusService.class.getName()); @ConfigProperty(name = "karavan.environment") String environment; @Inject InfinispanService infinispanService; @Inject DockerService dockerService; @Inject EventBus eventBus; @Scheduled(every = "{karavan.container.statistics.interval}", concurrentExecution = Scheduled.ConcurrentExecution.SKIP) void collectContainersStatistics() { if (infinispanService.isReady() && !ConfigService.inKubernetes()) { List<ContainerStatus> statusesInDocker = dockerService.collectContainersStatistics(); statusesInDocker.forEach(containerStatus -> { eventBus.send(ContainerStatusService.CONTAINER_STATUS, JsonObject.mapFrom(containerStatus)); }); } } @Scheduled(every = "{karavan.container.status.interval}", concurrentExecution = Scheduled.ConcurrentExecution.SKIP) void collectContainersStatuses() { if (infinispanService.isReady() && !ConfigService.inKubernetes()) { if (!ConfigService.inKubernetes()) { List<ContainerStatus> statusesInDocker = dockerService.collectContainersStatuses(); statusesInDocker.forEach(containerStatus -> { eventBus.send(ContainerStatusService.CONTAINER_STATUS, JsonObject.mapFrom(containerStatus)); }); cleanContainersStatuses(statusesInDocker); } } } void cleanContainersStatuses(List<ContainerStatus> statusesInDocker) { if (infinispanService.isReady() && !ConfigService.inKubernetes()) { List<String> namesInDocker = statusesInDocker.stream().map(ContainerStatus::getContainerName).toList(); List<ContainerStatus> statusesInInfinispan = infinispanService.getContainerStatuses(environment); // clean deleted statusesInInfinispan.stream() .filter(cs -> !checkTransit(cs)) .filter(cs -> !namesInDocker.contains(cs.getContainerName())) .forEach(containerStatus -> { infinispanService.deleteContainerStatus(containerStatus); infinispanService.deleteCamelStatuses(containerStatus.getProjectId(), containerStatus.getEnv()); }); } } private boolean checkTransit(ContainerStatus cs) { if (cs.getContainerId() == null && cs.getInTransit()) { return Instant.parse(cs.getInitDate()).until(Instant.now(), ChronoUnit.SECONDS) < 10; } return false; } @ConsumeEvent(value = CONTAINER_STATUS, blocking = true, ordered = true) public void saveContainerStatus(JsonObject data) { if (infinispanService.isReady()) { ContainerStatus newStatus = data.mapTo(ContainerStatus.class); ContainerStatus oldStatus = infinispanService.getContainerStatus(newStatus.getProjectId(), newStatus.getEnv(), newStatus.getContainerName()); if (oldStatus == null) { infinispanService.saveContainerStatus(newStatus); } else if (Objects.equals(oldStatus.getInTransit(), Boolean.FALSE)) { saveContainerStatus(newStatus, oldStatus); } else if (Objects.equals(oldStatus.getInTransit(), Boolean.TRUE)) { if (!Objects.equals(oldStatus.getState(), newStatus.getState()) || newStatus.getCpuInfo() == null || newStatus.getCpuInfo().isEmpty()) { saveContainerStatus(newStatus, oldStatus); } } } } @ConsumeEvent(value = CONTAINER_STATUS, blocking = true, ordered = true) public void checkProjectExists(JsonObject data) { if (infinispanService.isReady()) { ContainerStatus status = data.mapTo(ContainerStatus.class); if (status.getType().equals(ContainerStatus.ContainerType.project)) { Project project = infinispanService.getProject(status.getProjectId()); if (project == null) { project = new Project(status.getProjectId(), status.getProjectId(), status.getProjectId()); infinispanService.saveProject(project); } } } } private void saveContainerStatus(ContainerStatus newStatus, ContainerStatus oldStatus) { if (Objects.equals("exited", newStatus.getState()) || Objects.equals("dead", newStatus.getState())) { if (Objects.isNull(oldStatus.getFinished())) { newStatus.setFinished(Instant.now().toString()); } else if (Objects.nonNull(oldStatus.getFinished())) { return; } } if (newStatus.getCpuInfo() == null || newStatus.getCpuInfo().isEmpty()) { newStatus.setCpuInfo(oldStatus.getCpuInfo()); newStatus.setMemoryInfo(oldStatus.getMemoryInfo()); } infinispanService.saveContainerStatus(newStatus); } }
957
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/service/AuthService.java
/* * 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 org.eclipse.microprofile.config.ConfigProvider; import org.jboss.logging.Logger; import jakarta.enterprise.context.ApplicationScoped; import java.net.MalformedURLException; import java.util.Map; @ApplicationScoped public class AuthService { private static final Logger LOGGER = Logger.getLogger(AuthService.class.getName()); public String authType() { return ConfigProvider.getConfig().getValue("karavan.auth", String.class); } public Map<String, String> getSsoConfig() throws MalformedURLException { return Map.of("url", ConfigProvider.getConfig().getValue("karavan.frontend.auth-server-url", String.class)); } }
958
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/service/ConfigService.java
/* * 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.quarkus.runtime.StartupEvent; import org.apache.camel.karavan.shared.Configuration; import org.eclipse.microprofile.config.inject.ConfigProperty; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Objects; @ApplicationScoped public class ConfigService { @ConfigProperty(name = "karavan.title") String title; @ConfigProperty(name = "karavan.version") String version; @ConfigProperty(name = "karavan.environment") String environment; @ConfigProperty(name = "karavan.environments") List<String> environments; private Configuration configuration; private static Boolean inKubernetes; private static Boolean inDocker; void onStart(@Observes StartupEvent ev) { configuration = new Configuration( title, version, inKubernetes() ? "kubernetes" : "docker", environment, environments ); } public Configuration getConfiguration() { return configuration; } public static boolean inKubernetes() { if (inKubernetes == null) { inKubernetes = Objects.nonNull(System.getenv("KUBERNETES_SERVICE_HOST")); } return inKubernetes; } public static boolean inDocker() { if (inDocker == null) { inDocker = !inKubernetes() && Files.exists(Paths.get(".dockerenv")); } return inDocker; } }
959
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/KubernetesService.java
/* * 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.kubernetes; import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.LogWatch; import io.fabric8.kubernetes.client.informers.SharedIndexInformer; import io.fabric8.openshift.api.model.ImageStream; import io.fabric8.openshift.client.OpenShiftClient; import io.quarkus.runtime.configuration.ProfileManager; import io.smallrye.mutiny.tuples.Tuple2; import io.vertx.mutiny.core.eventbus.EventBus; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.infinispan.model.Project; import org.apache.camel.karavan.infinispan.model.ProjectFile; import org.apache.camel.karavan.code.CodeService; import org.apache.camel.karavan.service.ConfigService; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.eclipse.microprofile.health.HealthCheck; import org.eclipse.microprofile.health.HealthCheckResponse; import org.eclipse.microprofile.health.Readiness; import org.jboss.logging.Logger; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Default; import jakarta.enterprise.inject.Produces; import jakarta.inject.Inject; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; import static org.apache.camel.karavan.code.CodeService.APPLICATION_PROPERTIES_FILENAME; import static org.apache.camel.karavan.shared.Constants.*; @Default @Readiness @ApplicationScoped public class KubernetesService implements HealthCheck { private static final Logger LOGGER = Logger.getLogger(KubernetesService.class.getName()); protected static final int INFORMERS = 3; @Inject EventBus eventBus; @Inject InfinispanService infinispanService; private String namespace; @Produces public KubernetesClient kubernetesClient() { return new DefaultKubernetesClient(); } @Produces public OpenShiftClient openshiftClient() { return kubernetesClient().adapt(OpenShiftClient.class); } @ConfigProperty(name = "karavan.environment") public String environment; @ConfigProperty(name = "karavan.version") String version; List<SharedIndexInformer> informers = new ArrayList<>(INFORMERS); public void startInformers(String data) { try { stopInformers(); LOGGER.info("Starting Kubernetes Informers"); Map<String, String> labels = getRuntimeLabels(); KubernetesClient client = kubernetesClient(); SharedIndexInformer<Deployment> deploymentInformer = client.apps().deployments().inNamespace(getNamespace()) .withLabels(labels).inform(); deploymentInformer.addEventHandlerWithResyncPeriod(new DeploymentEventHandler(infinispanService, this), 30 * 1000L); informers.add(deploymentInformer); SharedIndexInformer<Service> serviceInformer = client.services().inNamespace(getNamespace()) .withLabels(labels).inform(); serviceInformer.addEventHandlerWithResyncPeriod(new ServiceEventHandler(infinispanService, this), 30 * 1000L); informers.add(serviceInformer); SharedIndexInformer<Pod> podRunInformer = client.pods().inNamespace(getNamespace()) .withLabels(labels).inform(); podRunInformer.addEventHandlerWithResyncPeriod(new PodEventHandler(infinispanService, this, eventBus), 30 * 1000L); informers.add(podRunInformer); LOGGER.info("Started Kubernetes Informers"); } catch (Exception e) { LOGGER.error("Error starting informers: " + e.getMessage()); } } @Override public HealthCheckResponse call() { if (ConfigService.inKubernetes()) { if (informers.size() == INFORMERS) { return HealthCheckResponse.named("Kubernetes").up().build(); } else { return HealthCheckResponse.named("Kubernetes").down().build(); } } else { return HealthCheckResponse.named("Kubernetesless").up().build(); } } public void stopInformers() { LOGGER.info("Stop Kubernetes Informers"); informers.forEach(SharedIndexInformer::close); informers.clear(); } public void runBuildProject(Project project, String script, List<String> env, String tag) { try (KubernetesClient client = kubernetesClient()) { String containerName = project.getProjectId() + BUILDER_SUFFIX; Map<String, String> labels = getLabels(containerName, project, ContainerStatus.ContainerType.build); // createPVC(containerName, labels); // create script configMap ConfigMap configMap = client.configMaps().inNamespace(getNamespace()).withName(containerName).get(); if (configMap == null) { configMap = getConfigMapForBuilder(containerName, labels); } configMap.setData(Map.of("build.sh", script)); client.resource(configMap).serverSideApply(); // Delete old build pod Pod old = client.pods().inNamespace(getNamespace()).withName(containerName).get(); if (old != null) { client.resource(old).delete(); } Pod pod = getBuilderPod(containerName, env, labels); Pod result = client.resource(pod).serverSideApply(); LOGGER.info("Created pod " + result.getMetadata().getName()); } } private Map<String, String> getLabels(String name, Project project, ContainerStatus.ContainerType type) { Map<String, String> labels = new HashMap<>(); labels.putAll(getRuntimeLabels()); labels.putAll(getPartOfLabels()); labels.put("app.kubernetes.io/name", name); labels.put(LABEL_PROJECT_ID, project.getProjectId()); if (type != null) { labels.put(LABEL_TYPE, type.name()); } return labels; } private Map<String, String> getRuntimeLabels() { Map<String, String> labels = new HashMap<>(); labels.put(isOpenshift() ? "app.openshift.io/runtime" : "app.kubernetes.io/runtime", CAMEL_PREFIX); return labels; } private Map<String, String> getPartOfLabels() { Map<String, String> labels = new HashMap<>(); labels.put(LABEL_PART_OF, KARAVAN_PREFIX); return labels; } private ConfigMap getConfigMapForBuilder(String name, Map<String, String> labels) { return new ConfigMapBuilder() .withMetadata(new ObjectMetaBuilder() .withName(name) .withLabels(labels) .withNamespace(getNamespace()) .build()) .build(); } private Pod getBuilderPod(String name, List<String> env, Map<String, String> labels) { List<EnvVar> envVars = new ArrayList<>(); env.stream().map(s -> s.split("=")).filter(s -> s.length > 0).forEach(parts -> { String varName = parts[0]; String varValue = parts[1]; envVars.add(new EnvVarBuilder().withName(varName).withValue(varValue).build()); }); envVars.add( new EnvVar("IMAGE_REGISTRY", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("image-registry", KARAVAN_SECRET_NAME, false)).build()) ); envVars.add( new EnvVar("IMAGE_REGISTRY_USERNAME", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("image-registry-username", KARAVAN_SECRET_NAME, false)).build()) ); envVars.add( new EnvVar("IMAGE_REGISTRY_PASSWORD", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("image-registry-password", KARAVAN_SECRET_NAME, false)).build()) ); envVars.add( new EnvVar("IMAGE_GROUP", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("image-group", KARAVAN_SECRET_NAME, false)).build()) ); envVars.add( new EnvVar("GIT_REPOSITORY", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("git-repository", KARAVAN_SECRET_NAME, false)).build()) ); envVars.add( new EnvVar("GIT_USERNAME", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("git-username", KARAVAN_SECRET_NAME, false)).build()) ); envVars.add( new EnvVar("GIT_PASSWORD", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("git-password", KARAVAN_SECRET_NAME, false)).build()) ); envVars.add( new EnvVar("GIT_BRANCH", null, new EnvVarSourceBuilder().withSecretKeyRef(new SecretKeySelector("git-branch", KARAVAN_SECRET_NAME, false)).build()) ); ObjectMeta meta = new ObjectMetaBuilder() .withName(name) .withLabels(labels) .withNamespace(getNamespace()) .build(); ContainerPort port = new ContainerPortBuilder() .withContainerPort(8080) .withName("http") .withProtocol("TCP") .build(); Container container = new ContainerBuilder() .withName(name) .withImage("ghcr.io/apache/camel-karavan-devmode:" + version) .withPorts(port) .withImagePullPolicy("Always") .withEnv(envVars) .withCommand("/bin/sh", "-c", "/karavan/builder/build.sh") .withVolumeMounts( new VolumeMountBuilder().withName("builder").withMountPath("/karavan/builder").withReadOnly(true).build() ) .build(); PodSpec spec = new PodSpecBuilder() .withTerminationGracePeriodSeconds(0L) .withContainers(container) .withRestartPolicy("Never") .withServiceAccount(KARAVAN_SERVICE_ACCOUNT) .withVolumes( new VolumeBuilder().withName("builder") .withConfigMap(new ConfigMapVolumeSourceBuilder().withName(name).withItems( new KeyToPathBuilder().withKey("build.sh").withPath("build.sh").build() ).withDefaultMode(511).build()).build() // new VolumeBuilder().withName("maven-settings") // .withConfigMap(new ConfigMapVolumeSourceBuilder() // .withName("karavan").build()).build() ).build(); return new PodBuilder() .withMetadata(meta) .withSpec(spec) .build(); } public Tuple2<LogWatch, KubernetesClient> getContainerLogWatch(String podName) { KubernetesClient client = kubernetesClient(); LogWatch logWatch = client.pods().inNamespace(getNamespace()).withName(podName).tailingLines(100).watchLog(); return Tuple2.of(logWatch, client); } public void rolloutDeployment(String name, String namespace) { try (KubernetesClient client = kubernetesClient()) { client.apps().deployments().inNamespace(namespace).withName(name).rolling().restart(); } catch (Exception ex) { LOGGER.error(ex.getMessage()); } } public void deleteDeployment(String name, String namespace) { try (KubernetesClient client = kubernetesClient()) { LOGGER.info("Delete deployment: " + name + " in the namespace: " + namespace); client.apps().deployments().inNamespace(namespace).withName(name).delete(); client.services().inNamespace(namespace).withName(name).delete(); } catch (Exception ex) { LOGGER.error(ex.getMessage()); } } public void deletePod(String name) { try (KubernetesClient client = kubernetesClient()) { LOGGER.info("Delete pod: " + name); client.pods().inNamespace(getNamespace()).withName(name).delete(); } catch (Exception ex) { LOGGER.error(ex.getMessage()); } } public List<String> getConfigMaps(String namespace) { List<String> result = new ArrayList<>(); try (KubernetesClient client = kubernetesClient()) { client.configMaps().inNamespace(namespace).list().getItems().forEach(configMap -> { String name = configMap.getMetadata().getName(); if (configMap.getData() != null) { configMap.getData().keySet().forEach(data -> result.add(name + "/" + data)); } }); } catch (Exception e) { LOGGER.error(e); } return result; } public List<String> getSecrets(String namespace) { List<String> result = new ArrayList<>(); try (KubernetesClient client = kubernetesClient()) { client.secrets().inNamespace(namespace).list().getItems().forEach(secret -> { String name = secret.getMetadata().getName(); if (secret.getData() != null) { secret.getData().keySet().forEach(data -> result.add(name + "/" + data)); } }); } catch (Exception e) { LOGGER.error(e); } return result; } public List<String> getServices(String namespace) { List<String> result = new ArrayList<>(); try (KubernetesClient client = kubernetesClient()) { client.services().inNamespace(namespace).list().getItems().forEach(service -> { String name = service.getMetadata().getName(); String host = name + "." + namespace + ".svc.cluster.local"; service.getSpec().getPorts().forEach(port -> result.add(name + "|" + host + ":" + port.getPort())); }); } catch (Exception e) { LOGGER.error(e); } return result; } public List<String> getProjectImageTags(String projectId, String namespace) { List<String> result = new ArrayList<>(); try { if (isOpenshift()) { ImageStream is = openshiftClient().imageStreams().inNamespace(namespace).withName(projectId).get(); if (is != null) { result.addAll(is.getSpec().getTags().stream().map(t -> t.getName()).sorted(Comparator.reverseOrder()).collect(Collectors.toList())); } } else { // TODO: Implement for Kubernetes/Minikube } } catch (Exception ex) { LOGGER.error(ex.getMessage()); } return result; } public void runDevModeContainer(Project project, String jBangOptions) { String name = project.getProjectId(); Map<String, String> labels = getLabels(name, project, ContainerStatus.ContainerType.devmode); try (KubernetesClient client = kubernetesClient()) { createPVC(name, labels); Pod old = client.pods().inNamespace(getNamespace()).withName(name).get(); if (old == null) { Map<String, String> containerResources = CodeService.DEFAULT_CONTAINER_RESOURCES; Pod pod = getDevModePod(name, jBangOptions, containerResources, labels); Pod result = client.resource(pod).createOrReplace(); LOGGER.info("Created pod " + result.getMetadata().getName()); } } createService(name, labels); } public void deleteDevModePod(String name, boolean deletePVC) { try (KubernetesClient client = kubernetesClient()) { LOGGER.info("Delete devmode pod: " + name + " in the namespace: " + getNamespace()); client.pods().inNamespace(getNamespace()).withName(name).delete(); client.services().inNamespace(getNamespace()).withName(name).delete(); if (deletePVC) { client.persistentVolumeClaims().inNamespace(getNamespace()).withName(name).delete(); } } catch (Exception ex) { LOGGER.error(ex.getMessage()); } } public ResourceRequirements getResourceRequirements(Map<String, String> containerResources) { return new ResourceRequirementsBuilder() .addToRequests("cpu", new Quantity(containerResources.get("requests.cpu"))) .addToRequests("memory", new Quantity(containerResources.get("requests.memory"))) .addToLimits("cpu", new Quantity(containerResources.get("limits.cpu"))) .addToLimits("memory", new Quantity(containerResources.get("limits.memory"))) .build(); } private Pod getDevModePod(String name, String jbangOptions, Map<String, String> containerResources, Map<String, String> labels) { ResourceRequirements resources = getResourceRequirements(containerResources); ObjectMeta meta = new ObjectMetaBuilder() .withName(name) .withLabels(labels) .withNamespace(getNamespace()) .build(); ContainerPort port = new ContainerPortBuilder() .withContainerPort(8080) .withName("http") .withProtocol("TCP") .build(); Container container = new ContainerBuilder() .withName(name) .withImage("ghcr.io/apache/camel-karavan-devmode:" + version) .withPorts(port) .withResources(resources) .withImagePullPolicy("Always") .withEnv(new EnvVarBuilder().withName(ENV_VAR_JBANG_OPTIONS).withValue(jbangOptions).build()) // .withVolumeMounts( // new VolumeMountBuilder().withName("maven-settings").withSubPath("maven-settings.xml") // .withMountPath("/karavan-config-map/maven-settings.xml").build() // ) .build(); PodSpec spec = new PodSpecBuilder() .withTerminationGracePeriodSeconds(0L) .withContainers(container) .withRestartPolicy("Never") .withVolumes( new VolumeBuilder().withName(name) .withNewPersistentVolumeClaim(name, false).build(), new VolumeBuilder().withName("maven-settings") .withConfigMap(new ConfigMapVolumeSourceBuilder() .withName("karavan").build()).build()) .build(); return new PodBuilder() .withMetadata(meta) .withSpec(spec) .build(); } private void createPVC(String podName, Map<String, String> labels) { try (KubernetesClient client = kubernetesClient()) { PersistentVolumeClaim old = client.persistentVolumeClaims().inNamespace(getNamespace()).withName(podName).get(); if (old == null) { PersistentVolumeClaim pvc = new PersistentVolumeClaimBuilder() .withNewMetadata() .withName(podName) .withNamespace(getNamespace()) .withLabels(labels) .endMetadata() .withNewSpec() .withResources(new ResourceRequirementsBuilder().withRequests(Map.of("storage", new Quantity("2Gi"))).build()) .withVolumeMode("Filesystem") .withAccessModes("ReadWriteOnce") .endSpec() .build(); client.resource(pvc).createOrReplace(); } } } private void createService(String name, Map<String, String> labels) { try (KubernetesClient client = kubernetesClient()) { ServicePortBuilder portBuilder = new ServicePortBuilder() .withName("http").withPort(80).withProtocol("TCP").withTargetPort(new IntOrString(8080)); Service service = new ServiceBuilder() .withNewMetadata() .withName(name) .withNamespace(getNamespace()) .withLabels(labels) .endMetadata() .withNewSpec() .withType("ClusterIP") .withPorts(portBuilder.build()) .withSelector(labels) .endSpec() .build(); client.resource(service).createOrReplace(); } } public Secret getKaravanSecret() { try (KubernetesClient client = kubernetesClient()) { return client.secrets().inNamespace(getNamespace()).withName("karavan").get(); } } public String getKaravanSecret(String key) { try (KubernetesClient client = kubernetesClient()) { Secret secret = client.secrets().inNamespace(getNamespace()).withName("karavan").get(); Map<String, String> data = secret.getData(); return decodeSecret(data.get(key)); } } private String decodeSecret(String data) { if (data != null) { return new String(Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8))); } return null; } public boolean isOpenshift() { try (KubernetesClient client = kubernetesClient()) { return ConfigService.inKubernetes() ? client.isAdaptable(OpenShiftClient.class) : false; } } public String getCluster() { try (KubernetesClient client = kubernetesClient()) { return client.getMasterUrl().getHost(); } } public String getNamespace() { if (namespace == null) { try (KubernetesClient client = kubernetesClient()) { namespace = ProfileManager.getLaunchMode().isDevOrTest() ? "karavan" : client.getNamespace(); } } return namespace; } }
960
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/DeploymentEventHandler.java
/* * 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.kubernetes; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.client.informers.ResourceEventHandler; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.DeploymentStatus; import org.jboss.logging.Logger; public class DeploymentEventHandler implements ResourceEventHandler<Deployment> { private static final Logger LOGGER = Logger.getLogger(DeploymentEventHandler.class.getName()); private final InfinispanService infinispanService; private final KubernetesService kubernetesService; public DeploymentEventHandler(InfinispanService infinispanService, KubernetesService kubernetesService) { this.infinispanService = infinispanService; this.kubernetesService = kubernetesService; } @Override public void onAdd(Deployment deployment) { try { LOGGER.info("onAdd " + deployment.getMetadata().getName()); DeploymentStatus ds = getDeploymentStatus(deployment); infinispanService.saveDeploymentStatus(ds); } catch (Exception e){ LOGGER.error(e.getMessage()); } } @Override public void onUpdate(Deployment oldDeployment, Deployment newDeployment) { try { LOGGER.info("onUpdate " + newDeployment.getMetadata().getName()); DeploymentStatus ds = getDeploymentStatus(newDeployment); infinispanService.saveDeploymentStatus(ds); } catch (Exception e){ LOGGER.error(e.getMessage()); } } @Override public void onDelete(Deployment deployment, boolean deletedFinalStateUnknown) { try { LOGGER.info("onDelete " + deployment.getMetadata().getName()); DeploymentStatus ds = new DeploymentStatus( deployment.getMetadata().getName(), deployment.getMetadata().getNamespace(), kubernetesService.getCluster(), kubernetesService.environment); infinispanService.deleteDeploymentStatus(ds); infinispanService.deleteCamelStatuses(deployment.getMetadata().getName(), ds.getEnv()); } catch (Exception e){ LOGGER.error(e.getMessage()); } } public DeploymentStatus getDeploymentStatus(Deployment deployment) { try { String dsImage = deployment.getSpec().getTemplate().getSpec().getContainers().get(0).getImage(); String imageName = dsImage.startsWith("image-registry.openshift-image-registry.svc") ? dsImage.replace("image-registry.openshift-image-registry.svc:5000/", "") : dsImage; return new DeploymentStatus( deployment.getMetadata().getName(), deployment.getMetadata().getNamespace(), kubernetesService.getCluster(), kubernetesService.environment, imageName, deployment.getSpec().getReplicas(), deployment.getStatus().getReadyReplicas(), deployment.getStatus().getUnavailableReplicas() ); } catch (Exception ex) { LOGGER.error(ex.getMessage()); return new DeploymentStatus( deployment.getMetadata().getName(), deployment.getMetadata().getNamespace(), kubernetesService.getCluster(), kubernetesService.environment); } } }
961
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/ServiceEventHandler.java
/* * 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.kubernetes; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.client.informers.ResourceEventHandler; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.ServiceStatus; import org.jboss.logging.Logger; public class ServiceEventHandler implements ResourceEventHandler<Service> { private static final Logger LOGGER = Logger.getLogger(ServiceEventHandler.class.getName()); private InfinispanService infinispanService; private KubernetesService kubernetesService; public ServiceEventHandler(InfinispanService infinispanService, KubernetesService kubernetesService) { this.infinispanService = infinispanService; this.kubernetesService = kubernetesService; } @Override public void onAdd(Service service) { try { LOGGER.info("onAdd " + service.getMetadata().getName()); ServiceStatus ds = getServiceStatus(service); infinispanService.saveServiceStatus(ds); } catch (Exception e){ LOGGER.error(e.getMessage()); } } @Override public void onUpdate(Service oldService, Service newService) { try { LOGGER.info("onUpdate " + newService.getMetadata().getName()); ServiceStatus ds = getServiceStatus(newService); infinispanService.saveServiceStatus(ds); } catch (Exception e){ LOGGER.error(e.getMessage()); } } @Override public void onDelete(Service service, boolean deletedFinalStateUnknown) { try { LOGGER.info("onDelete " + service.getMetadata().getName()); ServiceStatus ds = new ServiceStatus( service.getMetadata().getName(), service.getMetadata().getNamespace(), kubernetesService.getCluster(), kubernetesService.environment); infinispanService.deleteServiceStatus(ds); } catch (Exception e){ LOGGER.error(e.getMessage()); } } public ServiceStatus getServiceStatus(Service service) { try { return new ServiceStatus( service.getMetadata().getName(), service.getMetadata().getNamespace(), kubernetesService.environment, kubernetesService.getCluster(), service.getSpec().getPorts().get(0).getPort(), service.getSpec().getPorts().get(0).getTargetPort().getIntVal(), service.getSpec().getClusterIP(), service.getSpec().getType() ); } catch (Exception ex) { LOGGER.error(ex.getMessage()); return new ServiceStatus( service.getMetadata().getName(), service.getMetadata().getNamespace(), kubernetesService.getCluster(), kubernetesService.environment); } } }
962
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/kubernetes/PodEventHandler.java
/* * 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.kubernetes; import io.fabric8.kubernetes.api.model.ContainerBuilder; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.client.informers.ResourceEventHandler; import io.vertx.core.json.JsonObject; import io.vertx.mutiny.core.eventbus.EventBus; import org.apache.camel.karavan.infinispan.InfinispanService; import org.apache.camel.karavan.infinispan.model.ContainerStatus; import org.apache.camel.karavan.infinispan.model.ProjectFile; import org.jboss.logging.Logger; import java.util.List; import java.util.Objects; import static org.apache.camel.karavan.code.CodeService.DEFAULT_CONTAINER_RESOURCES; import static org.apache.camel.karavan.shared.Constants.LABEL_PROJECT_ID; import static org.apache.camel.karavan.service.ContainerStatusService.CONTAINER_STATUS; import static org.apache.camel.karavan.shared.Constants.LABEL_TYPE; public class PodEventHandler implements ResourceEventHandler<Pod> { private static final Logger LOGGER = Logger.getLogger(PodEventHandler.class.getName()); private final InfinispanService infinispanService; private final KubernetesService kubernetesService; private final EventBus eventBus; public PodEventHandler(InfinispanService infinispanService, KubernetesService kubernetesService, EventBus eventBus) { this.infinispanService = infinispanService; this.kubernetesService = kubernetesService; this.eventBus = eventBus; } @Override public void onAdd(Pod pod) { try { LOGGER.info("onAdd " + pod.getMetadata().getName()); ContainerStatus ps = getPodStatus(pod); if (ps != null) { eventBus.send(CONTAINER_STATUS, JsonObject.mapFrom(ps)); } } catch (Exception e) { LOGGER.error(e.getMessage(), e.getCause()); } } @Override public void onUpdate(Pod oldPod, Pod newPod) { try { LOGGER.info("onUpdate " + newPod.getMetadata().getName()); if (!newPod.isMarkedForDeletion() && newPod.getMetadata().getDeletionTimestamp() == null) { ContainerStatus ps = getPodStatus(newPod); if (ps != null) { eventBus.send(CONTAINER_STATUS, JsonObject.mapFrom(ps)); } } } catch (Exception e) { LOGGER.error(e.getMessage(), e.getCause()); } } @Override public void onDelete(Pod pod, boolean deletedFinalStateUnknown) { try { LOGGER.info("onDelete " + pod.getMetadata().getName()); String deployment = pod.getMetadata().getLabels().get("app"); String projectId = deployment != null ? deployment : pod.getMetadata().getLabels().get(LABEL_PROJECT_ID); infinispanService.deleteContainerStatus(projectId, kubernetesService.environment, pod.getMetadata().getName()); infinispanService.deleteCamelStatuses(projectId, kubernetesService.environment); } catch (Exception e) { LOGGER.error(e.getMessage(), e.getCause()); } } public ContainerStatus getPodStatus(Pod pod) { String deployment = pod.getMetadata().getLabels().get("app"); String projectId = deployment != null ? deployment : pod.getMetadata().getLabels().get(LABEL_PROJECT_ID); String type = pod.getMetadata().getLabels().get(LABEL_TYPE); ContainerStatus.ContainerType containerType = deployment != null ? ContainerStatus.ContainerType.project : (type != null ? ContainerStatus.ContainerType.valueOf(type) : ContainerStatus.ContainerType.unknown); try { boolean ready = pod.getStatus().getConditions().stream().anyMatch(c -> c.getType().equals("Ready") && c.getStatus().equals("True")); boolean running = Objects.equals(pod.getStatus().getPhase(), "Running"); boolean failed = Objects.equals(pod.getStatus().getPhase(), "Failed"); boolean succeeded = Objects.equals(pod.getStatus().getPhase(), "Succeeded"); String creationTimestamp = pod.getMetadata().getCreationTimestamp(); ResourceRequirements defaultRR = kubernetesService.getResourceRequirements(DEFAULT_CONTAINER_RESOURCES); ResourceRequirements resourceRequirements = pod.getSpec().getContainers().stream().findFirst() .orElse(new ContainerBuilder().withResources(defaultRR).build()).getResources(); String requestMemory = resourceRequirements.getRequests().getOrDefault("memory", new Quantity()).toString(); String requestCpu = resourceRequirements.getRequests().getOrDefault("cpu", new Quantity()).toString(); String limitMemory = resourceRequirements.getLimits().getOrDefault("memory", new Quantity()).toString(); String limitCpu = resourceRequirements.getLimits().getOrDefault("cpu", new Quantity()).toString(); ContainerStatus status = new ContainerStatus( pod.getMetadata().getName(), List.of(ContainerStatus.Command.delete), projectId, kubernetesService.environment, containerType, requestMemory + " / " + limitMemory, requestCpu + " / " + limitCpu, creationTimestamp); status.setContainerId(pod.getMetadata().getName()); status.setPhase(pod.getStatus().getPhase()); status.setPodIP(pod.getStatus().getPodIP()); if (ready) { status.setState(ContainerStatus.State.running.name()); } else if (failed) { status.setState(ContainerStatus.State.dead.name()); } else if (succeeded) { status.setState(ContainerStatus.State.exited.name()); } else { status.setState(ContainerStatus.State.created.name()); } return status; } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex.getCause()); return null; } } }
963
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git/GitService.java
/* * 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.git; import io.fabric8.kubernetes.api.model.Secret; import io.smallrye.mutiny.tuples.Tuple2; import io.vertx.core.Vertx; import org.apache.camel.karavan.git.model.GitConfig; import org.apache.camel.karavan.git.model.GitRepo; import org.apache.camel.karavan.git.model.GitRepoFile; import org.apache.camel.karavan.infinispan.model.*; import org.apache.camel.karavan.kubernetes.KubernetesService; import org.apache.camel.karavan.registry.RegistryConfig; import org.apache.camel.karavan.service.ConfigService; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.PullCommand; import org.eclipse.jgit.api.PullResult; import org.eclipse.jgit.api.RemoteAddCommand; import org.eclipse.jgit.api.errors.GitAPIException; 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.ObjectId; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.FetchResult; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.URIish; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.faulttolerance.Retry; import org.jboss.logging.Logger; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; @ApplicationScoped public class GitService { @Inject Vertx vertx; @Inject KubernetesService kubernetesService; private Git gitForImport; private static final Logger LOGGER = Logger.getLogger(GitService.class.getName()); public Git getGitForImport(){ if (gitForImport == null) { try { gitForImport = getGit(true, vertx.fileSystem().createTempDirectoryBlocking("import")); } catch (Exception e) { LOGGER.error("Error", e); } } return gitForImport; } public GitConfig getGitConfig() { String propertiesPrefix = "karavan."; String branch = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-branch", String.class); if (ConfigService.inKubernetes()) { String uri = kubernetesService.getKaravanSecret("git-repository"); String username = kubernetesService.getKaravanSecret("git-username"); String password = kubernetesService.getKaravanSecret("git-password"); String branchInSecret = kubernetesService.getKaravanSecret("git-branch"); branch = branchInSecret != null ? branchInSecret : branch; return new GitConfig(uri, username, password, branch); } else if (ConfigService.inDocker()) { String uri = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-repository", String.class); String username = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-username", String.class); String password = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-password", String.class); return new GitConfig(uri, username, password, branch); } else { Boolean giteaInstall = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-install-gitea", Boolean.class); String uri = giteaInstall ? "http://localhost:3000/karavan/karavan.git" : ConfigProvider.getConfig().getValue(propertiesPrefix + "git-repository", String.class); String username = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-username", String.class); String password = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-password", String.class); return new GitConfig(uri, username, password, branch); } } public List<String> getEnvForBuild() { GitConfig gitConfig = getGitConfigForBuilder(); return List.of( "GIT_REPOSITORY=" + gitConfig.getUri(), "GIT_USERNAME=" + gitConfig.getUsername(), "GIT_PASSWORD=" + gitConfig.getPassword(), "GIT_BRANCH=" + gitConfig.getBranch()); } public GitConfig getGitConfigForBuilder() { String propertiesPrefix = "karavan."; String branch = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-branch", String.class); if (ConfigService.inKubernetes()) { LOGGER.info("inKubernetes " + kubernetesService.getNamespace()); Secret secret = kubernetesService.getKaravanSecret(); String uri = kubernetesService.getKaravanSecret("git-repository"); String username = kubernetesService.getKaravanSecret("git-username"); String password = kubernetesService.getKaravanSecret("git-password"); if (secret.getData().containsKey("git-branch")) { branch = kubernetesService.getKaravanSecret("git-branch"); } return new GitConfig(uri, username, password, branch); } else { String uri = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-repository", String.class); String username = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-username", String.class); String password = ConfigProvider.getConfig().getValue(propertiesPrefix + "git-password", String.class); return new GitConfig(uri, username, password, branch); } } public RevCommit commitAndPushProject(Project project, List<ProjectFile> files, String message) throws GitAPIException, IOException, URISyntaxException { LOGGER.info("Commit and push project " + project.getProjectId()); GitConfig gitConfig = getGitConfig(); CredentialsProvider cred = new UsernamePasswordCredentialsProvider(gitConfig.getUsername(), gitConfig.getPassword()); String uuid = UUID.randomUUID().toString(); String folder = vertx.fileSystem().createTempDirectoryBlocking(uuid); LOGGER.info("Temp folder created " + folder); Git git = null; try { git = clone(folder, gitConfig.getUri(), gitConfig.getBranch(), cred); checkout(git, false, null, null, gitConfig.getBranch()); } catch (RefNotFoundException | TransportException e) { LOGGER.error("New repository"); git = init(folder, gitConfig.getUri(), gitConfig.getBranch()); } catch (Exception e) { LOGGER.error("Error", e); } writeProjectToFolder(folder, project, files); addDeletedFilesToIndex(git, folder, project, files); return commitAddedAndPush(git, gitConfig.getBranch(), cred, message); } public List<GitRepo> readProjectsToImport() { Git importGit = getGitForImport(); if (importGit != null) { return readProjectsFromRepository(importGit, new String[0]); } return new ArrayList<>(0); } public GitRepo readProjectFromRepository(String projectId) { Git git = null; try { git = getGit(true, vertx.fileSystem().createTempDirectoryBlocking(UUID.randomUUID().toString())); } catch (Exception e) { LOGGER.error("Error", e); } return readProjectsFromRepository(git, projectId).get(0); } private List<GitRepo> readProjectsFromRepository(Git git, String... filter) { LOGGER.info("Read projects..."); List<GitRepo> result = new ArrayList<>(); try { String folder = git.getRepository().getDirectory().getAbsolutePath().replace("/.git", ""); List<String> projects = readProjectsFromFolder(folder, filter); for (String project : projects) { Map<String, String> filesRead = readProjectFilesFromFolder(folder, project); List<GitRepoFile> files = new ArrayList<>(filesRead.size()); for (Map.Entry<String, String> entry : filesRead.entrySet()) { String name = entry.getKey(); String body = entry.getValue(); Tuple2<String, Integer> fileCommit = lastCommit(git, project + File.separator + name); files.add(new GitRepoFile(name, Integer.valueOf(fileCommit.getItem2()).longValue() * 1000, body)); } Tuple2<String, Integer> commit = lastCommit(git, project); GitRepo repo = new GitRepo(project, commit.getItem1(), Integer.valueOf(commit.getItem2()).longValue() * 1000, files); result.add(repo); } return result; } catch (RefNotFoundException e) { LOGGER.error("New repository"); return result; } catch (Exception e) { LOGGER.error("Error", e); return result; } } public Git getGit(boolean checkout, String folder) throws GitAPIException, IOException, URISyntaxException { LOGGER.info("Git checkout"); GitConfig gitConfig = getGitConfig(); CredentialsProvider cred = new UsernamePasswordCredentialsProvider(gitConfig.getUsername(), gitConfig.getPassword()); LOGGER.info("Temp folder created " + folder); Git git = null; try { git = clone(folder, gitConfig.getUri(), gitConfig.getBranch(), cred); if (checkout) { checkout(git, false, null, null, gitConfig.getBranch()); } } catch (RefNotFoundException | TransportException e) { LOGGER.error("New repository"); git = init(folder, gitConfig.getUri(), gitConfig.getBranch()); } catch (Exception e) { LOGGER.error("Error", e); } return git; } private List<Tuple2<String, String>> readKameletsFromFolder(String folder) { LOGGER.info("Read kamelets from " + folder); List<Tuple2<String, String>> kamelets = new ArrayList<>(); vertx.fileSystem().readDirBlocking(folder).stream().filter(f -> f.endsWith("kamelet.yaml")).forEach(f -> { Path path = Paths.get(f); try { String yaml = Files.readString(path); kamelets.add(Tuple2.of(path.getFileName().toString(), yaml)); } catch (IOException e) { LOGGER.error("Error during file read", e); } }); return kamelets; } private List<String> readProjectsFromFolder(String folder, String... filter) { LOGGER.info("Read projects from " + folder); List<String> files = new ArrayList<>(); vertx.fileSystem().readDirBlocking(folder).forEach(path -> { String[] filenames = path.split(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.stream(filter).filter(f -> f.equals(folderName)).findFirst().isPresent()) { LOGGER.info("Importing project from folder " + folderName); files.add(folderName); } } }); return files; } private Map<String, String> readProjectFilesFromFolder(String repoFolder, String projectFolder) { LOGGER.infof("Read 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(File.separator); String filename = filenames[filenames.length - 1]; Path path = Paths.get(f); if (!filename.startsWith(".") && !Files.isDirectory(path)) { LOGGER.info("Importing file " + 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, Project project, List<ProjectFile> files) throws IOException { Files.createDirectories(Paths.get(folder, project.getProjectId())); LOGGER.info("Write files for project " + project.getProjectId()); files.forEach(file -> { try { LOGGER.info("Add file " + file.getName()); Files.writeString(Paths.get(folder, project.getProjectId(), file.getName()), file.getCode()); } catch (IOException e) { LOGGER.error("Error during file write", e); } }); } private void addDeletedFilesToIndex(Git git, String folder, Project project, List<ProjectFile> files) throws IOException { Path path = Paths.get(folder, project.getProjectId()); LOGGER.info("Add deleted files to git index for project " + project.getProjectId()); vertx.fileSystem().readDirBlocking(path.toString()).forEach(f -> { String[] filenames = f.split(File.separator); String filename = filenames[filenames.length - 1]; LOGGER.info("Checking file " + filename); if (files.stream().filter(pf -> Objects.equals(pf.getName(), filename)).count() == 0) { try { LOGGER.info("Add deleted file " + filename); git.rm().addFilepattern(project.getProjectId() + File.separator + filename).call(); } catch (GitAPIException e) { throw new RuntimeException(e); } } }); } public RevCommit commitAddedAndPush(Git git, String branch, CredentialsProvider cred, String message) throws GitAPIException { LOGGER.info("Commit and push changes"); LOGGER.info("Git add: " + git.add().addFilepattern(".").call()); RevCommit commit = git.commit().setMessage(message).call(); LOGGER.info("Git commit: " + commit); Iterable<PushResult> result = git.push().add(branch).setRemote("origin").setCredentialsProvider(cred).call(); LOGGER.info("Git push: " + result); return commit; } public Git init(String dir, String uri, String branch) throws GitAPIException, IOException, URISyntaxException { Git git = Git.init().setInitialBranch(branch).setDirectory(Path.of(dir).toFile()).call(); // git.branchCreate().setName(branch).call(); addRemote(git, uri); return git; } private void addDeletedFolderToIndex(Git git, String folder, String projectId, List<ProjectFile> files) { LOGGER.infof("Add folder %s to git index.", projectId); try { git.rm().addFilepattern(projectId + File.separator).call(); } catch (GitAPIException e) { throw new RuntimeException(e); } } public void deleteProject(String projectId, List<ProjectFile> files) { LOGGER.info("Delete and push project " + projectId); GitConfig gitConfig = getGitConfig(); CredentialsProvider cred = new UsernamePasswordCredentialsProvider(gitConfig.getUsername(), gitConfig.getPassword()); String uuid = UUID.randomUUID().toString(); String folder = vertx.fileSystem().createTempDirectoryBlocking(uuid); String commitMessage = "Project " + projectId + " is deleted"; LOGGER.infof("Temp folder %s is created for deletion of project %s", folder, projectId); Git git = null; try { git = clone(folder, gitConfig.getUri(), gitConfig.getBranch(), cred); checkout(git, false, null, null, gitConfig.getBranch()); addDeletedFolderToIndex(git, folder, projectId, files); commitAddedAndPush(git, gitConfig.getBranch(), cred, commitMessage); LOGGER.info("Delete Temp folder " + folder); vertx.fileSystem().deleteRecursiveBlocking(folder, true); LOGGER.infof("Project %s deleted from Git", projectId); } catch (RefNotFoundException e) { LOGGER.error("Repository not found"); } catch (Exception e) { LOGGER.error("Error", e); throw new RuntimeException(e); } } private Git clone(String dir, String uri, String branch, CredentialsProvider cred) throws GitAPIException, URISyntaxException { CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setCloneAllBranches(false); cloneCommand.setDirectory(Paths.get(dir).toFile()); cloneCommand.setURI(uri); cloneCommand.setBranch(branch); cloneCommand.setCredentialsProvider(cred); Git git = cloneCommand.call(); addRemote(git, uri); return git; } private void addRemote(Git git, String uri) throws URISyntaxException, GitAPIException { // add remote repo: RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName("origin"); remoteAddCommand.setUri(new URIish(uri)); remoteAddCommand.call(); } private void fetch(Git git, CredentialsProvider cred) throws GitAPIException { // fetch: FetchCommand fetchCommand = git.fetch(); fetchCommand.setCredentialsProvider(cred); FetchResult result = fetchCommand.call(); } private void pull(Git git, CredentialsProvider cred) throws GitAPIException { // pull: PullCommand pullCommand = git.pull(); pullCommand.setCredentialsProvider(cred); PullResult result = pullCommand.call(); } private void checkout(Git git, boolean create, String path, String startPoint, String branch) throws GitAPIException { // create branch: CheckoutCommand checkoutCommand = git.checkout(); checkoutCommand.setName(branch); checkoutCommand.setCreateBranch(create); if (startPoint != null) { checkoutCommand.setStartPoint(startPoint); } if (path != null) { checkoutCommand.addPath(path); } 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(File.separator); if (parts.length > 0) { files.add(parts[0]); } } }); } catch (IOException e) { LOGGER.error("Error", e); } } return files; } @Retry(maxRetries = 100, delay = 2000) public boolean checkGit() throws Exception { LOGGER.info("Check git"); GitConfig gitConfig = getGitConfig(); CredentialsProvider cred = new UsernamePasswordCredentialsProvider(gitConfig.getUsername(), gitConfig.getPassword()); String uuid = UUID.randomUUID().toString(); String folder = vertx.fileSystem().createTempDirectoryBlocking(uuid); try (Git git = clone(folder, gitConfig.getUri(), gitConfig.getBranch(), cred)) { LOGGER.info("Git is ready"); } return true; } }
964
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git/GiteaService.java
/* * 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.git; import io.vertx.core.json.JsonObject; import io.vertx.mutiny.core.Vertx; import io.vertx.mutiny.core.buffer.Buffer; 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.git.model.GitConfig; import org.apache.camel.karavan.service.ConfigService; import org.eclipse.microprofile.faulttolerance.Retry; import org.jboss.logging.Logger; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; @ApplicationScoped public class GiteaService { private static final Logger LOGGER = Logger.getLogger(GiteaService.class.getName()); @Inject Vertx vertx; @Inject GitService gitService; String token; WebClient webClient; private WebClient getWebClient() { if (webClient == null) { webClient = WebClient.create(vertx); } return webClient; } @Retry(maxRetries = 100, delay = 2000) public void install() throws Exception { LOGGER.info("Install Gitea"); HttpResponse<Buffer> result = getWebClient().postAbs(getGiteaBaseUrl()).timeout(1000) .putHeader("Content-Type", "application/x-www-form-urlencoded") .sendBuffer(Buffer.buffer( "db_type=sqlite3&db_host=localhost%3A3306&db_user=root&db_passwd=&db_name=gitea" + "&ssl_mode=disable&db_schema=&db_path=%2Fvar%2Flib%2Fgitea%2Fdata%2Fgitea.db&app_name=Karavan" + "&repo_root_path=%2Fvar%2Flib%2Fgitea%2Fgit%2Frepositories&lfs_root_path=%2Fvar%2Flib%2Fgitea%2Fgit%2Flfs&run_user=git" + "&domain=localhost&ssh_port=2222&http_port=3000&app_url=http%3A%2F%2Flocalhost%3A3000%2F&log_root_path=%2Fvar%2Flib%2Fgitea%2Fdata%2Flog" + "&smtp_addr=&smtp_port=&smtp_from=&smtp_user=&smtp_passwd=&enable_federated_avatar=on&enable_open_id_sign_in=on" + "&enable_open_id_sign_up=on&default_allow_create_organization=on&default_enable_timetracking=on" + "&no_reply_address=noreply.localhost&password_algorithm=pbkdf2&admin_name=&admin_email=&admin_passwd=&admin_confirm_passwd=" )) .subscribeAsCompletionStage().toCompletableFuture().get(); if (result.statusCode() != 200 && result.statusCode() != 405) { LOGGER.info("Gitea not ready"); throw new Exception("Gitea not ready"); } LOGGER.info("Installed Gitea"); } @Retry(maxRetries = 100, delay = 2000) public void createRepository() throws Exception { LOGGER.info("Creating Gitea Repository"); String token = generateToken(); HttpResponse<Buffer> result = getWebClient().postAbs(getGiteaBaseUrl() + "/api/v1/user/repos").timeout(500) .putHeader("Content-Type", "application/json") .bearerTokenAuthentication(token) .sendJsonObject(new JsonObject(Map.of( "auto_init", true, "default_branch", "main", "description", "karavan", "name", "karavan", "private", true ))) .subscribeAsCompletionStage().toCompletableFuture().get(); if (result.statusCode() == 409 && result.bodyAsJsonObject().getString("message").contains("already exists")) { JsonObject res = result.bodyAsJsonObject(); deleteToken("karavan"); } else if (result.statusCode() == 201) { JsonObject res = result.bodyAsJsonObject(); deleteToken("karavan"); } else { LOGGER.info("Error creating Gitea repository"); throw new Exception("Error creating Gitea repository"); } LOGGER.info("Created Gitea Repository"); } @Retry(maxRetries = 100, delay = 2000) protected String generateToken() throws Exception { if (token != null) { return token; } LOGGER.info("Creating Gitea User Token"); GitConfig config = gitService.getGitConfig(); String uri = getGiteaBaseUrl() + "/api/v1/users/" + config.getUsername() + "/tokens"; HttpResponse<Buffer> result = getWebClient().postAbs(uri).timeout(500) .putHeader("Content-Type", "application/json") .putHeader("accept", "application/json") .basicAuthentication(config.getUsername(), config.getPassword()) .sendJsonObject(new JsonObject( Map.of("name", "karavan", "scopes", List.of("write:repository", "write:user"))) ).subscribeAsCompletionStage().toCompletableFuture().get(); if (result.statusCode() == 400) { JsonObject res = result.bodyAsJsonObject(); return res.getString("sha1"); } else if (result.statusCode() == 201) { JsonObject res = result.bodyAsJsonObject(); token = res.getString("sha1"); LOGGER.info("Gitea User Token received"); return token; } else { LOGGER.info("Error getting token"); throw new Exception("Error getting token"); } } protected void deleteToken(String token) throws Exception { LOGGER.info("Deleting Gitea User Token"); GitConfig config = gitService.getGitConfig(); HttpResponse<Buffer> result = getWebClient() .deleteAbs(getGiteaBaseUrl() + "/api/v1/users/" + config.getUsername() + "/tokens/" + token) .timeout(500) .putHeader("Content-Type", "application/json") .putHeader("accept", "application/json") .basicAuthentication(config.getUsername(), config.getPassword()) .send().subscribeAsCompletionStage().toCompletableFuture().get(); if (result.statusCode() == 204) { LOGGER.info("Deleted Gitea User Token"); } } private String getGiteaBaseUrl() throws MalformedURLException { if (ConfigService.inDocker()) { return "http://gitea:3000"; } else if (ConfigService.inKubernetes()) { String uri = gitService.getGitConfig().getUri(); URL url = new URL(uri); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); return protocol + "://" + host + (port > 0 ? ":" + port : ""); } else { return "http://localhost:3000"; } } }
965
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git/model/GitConfig.java
/* * 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.git.model; public class GitConfig { private String uri; private String username; private String password; private String branch; public GitConfig(String uri, String username, String password, String branch) { this.uri = uri; this.username = username; this.password = password; this.branch = branch; } 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; } }
966
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git/model/GitRepoFile.java
/* * 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.git.model; public class GitRepoFile { private String name; private Long lastCommitTimestamp; private String body; public GitRepoFile(String name, Long lastCommitTimestamp, String body) { this.name = name; this.lastCommitTimestamp = lastCommitTimestamp; this.body = body; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getLastCommitTimestamp() { return lastCommitTimestamp; } public void setLastCommitTimestamp(Long lastCommitTimestamp) { this.lastCommitTimestamp = lastCommitTimestamp; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
967
0
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git
Create_ds/camel-karavan/karavan-web/karavan-app/src/main/java/org/apache/camel/karavan/git/model/GitRepo.java
/* * 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.git.model; import java.util.List; public class GitRepo { private String name; private String commitId; private Long lastCommitTimestamp; private List<GitRepoFile> files; public GitRepo(String name, String commitId, Long lastCommitTimestamp, List<GitRepoFile> files) { this.name = name; this.commitId = commitId; this.lastCommitTimestamp = lastCommitTimestamp; this.files = files; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCommitId() { return commitId; } public void setCommitId(String commitId) { this.commitId = commitId; } public Long getLastCommitTimestamp() { return lastCommitTimestamp; } public void setLastCommitTimestamp(Long lastCommitTimestamp) { this.lastCommitTimestamp = lastCommitTimestamp; } public List<GitRepoFile> getFiles() { return files; } public void setFiles(List<GitRepoFile> files) { this.files = files; } }
968
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/provider/MyWriter.java
/** * 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.cxf.dosgi.dsw.handlers.rest.provider; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.osgi.service.component.annotations.Component; @Component// (// immediate = true, // property = // { "org.apache.cxf.dosgi.IntentName=mytask", // } // ) @Provider public class MyWriter implements MessageBodyWriter<Task> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == Task.class; } @Override public long getSize(Task t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return 0; } @Override public void writeTo(Task t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try (OutputStreamWriter writer = new OutputStreamWriter(entityStream)) { writer.write(t.getName()); } } }
969
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/provider/MyReader.java
/** * 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.cxf.dosgi.dsw.handlers.rest.provider; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; @Provider public class MyReader implements MessageBodyReader<Task> { @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == Task.class; } @Override public Task readFrom(Class<Task> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try (Reader reader = new InputStreamReader(entityStream); BufferedReader breader = new BufferedReader(reader)) { String name = breader.readLine(); return new Task(name); } } }
970
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/provider/Task.java
/** * 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.cxf.dosgi.dsw.handlers.rest.provider; public class Task { String name; public Task() { } public Task(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
971
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/provider/RsProviderCustomTest.java
/** * 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.cxf.dosgi.dsw.handlers.rest.provider; import java.util.Arrays; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.apache.aries.rsa.spi.Endpoint; import org.apache.cxf.dosgi.common.httpservice.HttpServiceManager; import org.apache.cxf.dosgi.common.intent.impl.IntentManagerImpl; import org.apache.cxf.dosgi.dsw.handlers.rest.RsConstants; import org.apache.cxf.dosgi.dsw.handlers.rest.RsProvider; import org.apache.cxf.jaxrs.client.WebClient; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Test; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.service.remoteserviceadmin.RemoteConstants; public class RsProviderCustomTest { @Test public void testCustomProvider() throws Exception { RsProvider rsProvider = new RsProvider(); HttpServiceManager httpServiceManager = new HttpServiceManager(); Dictionary<String, Object> config = new Hashtable<>(); httpServiceManager.initFromConfig(config); rsProvider.setHttpServiceManager(httpServiceManager); IntentManagerImpl intentManager = new IntentManagerImpl(); addIntent(intentManager, "my", new MyWriter(), new MyReader()); rsProvider.setIntentManager(intentManager); TaskServiceImpl taskService = new TaskServiceImpl(); BundleContext callingContext = EasyMock.createMock(BundleContext.class); Map<String, Object> props = new HashMap<>(); props.put(Constants.OBJECTCLASS, new String[]{TaskService.class.getName()}); String serviceAddress = "http://localhost:9181/"; props.put(RsConstants.RS_ADDRESS_PROPERTY, serviceAddress); props.put(RemoteConstants.SERVICE_EXPORTED_INTENTS, "my"); Class<?>[] ifaces = new Class[]{TaskService.class}; try (Endpoint endpoint = rsProvider.exportService(taskService, callingContext, props, ifaces)) { Assert.assertEquals(serviceAddress, endpoint.description().getId()); Assert.assertEquals("my", endpoint.description().getIntents().iterator().next()); List<Object> providers = Arrays.asList((Object)MyReader.class); Task task1 = WebClient.create(serviceAddress, providers).path("/task").get(Task.class); Assert.assertEquals("test", task1.getName()); TaskService proxy = (TaskService)rsProvider.importEndpoint(TaskService.class.getClassLoader(), callingContext, ifaces, endpoint.description()); Task task = proxy.getTask(); Assert.assertEquals("test", task.getName()); } } private void addIntent(IntentManagerImpl intentManager, String name, Object... intents) { Callable<List<Object>> provider = intentProvider(intents); intentManager.addIntent(provider, name); } private Callable<List<Object>> intentProvider(final Object... intents) { return new Callable<List<Object>>() { @Override public List<Object> call() { return Arrays.asList(intents); } }; } }
972
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/provider/TaskService.java
/** * 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.cxf.dosgi.dsw.handlers.rest.provider; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/task") public interface TaskService { @GET Task getTask(); }
973
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/provider/TaskServiceImpl.java
/** * 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.cxf.dosgi.dsw.handlers.rest.provider; public class TaskServiceImpl implements TaskService { @Override public Task getTask() { return new Task("test"); } }
974
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/simple/Task.java
/** * 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.cxf.dosgi.dsw.handlers.rest.simple; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Task { String name; public Task() { } public Task(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
975
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/simple/TaskService.java
/** * 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.cxf.dosgi.dsw.handlers.rest.simple; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/task") public interface TaskService { @GET Task getTask(); }
976
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/simple/TaskServiceImpl.java
/** * 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.cxf.dosgi.dsw.handlers.rest.simple; public class TaskServiceImpl implements TaskService { @Override public Task getTask() { return new Task("test"); } }
977
0
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest
Create_ds/cxf-dosgi/provider-rs/src/test/java/org/apache/cxf/dosgi/dsw/handlers/rest/simple/RsProviderTest.java
/** * 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.cxf.dosgi.dsw.handlers.rest.simple; import java.io.IOException; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import org.apache.aries.rsa.spi.Endpoint; import org.apache.cxf.dosgi.common.httpservice.HttpServiceManager; import org.apache.cxf.dosgi.common.intent.impl.IntentManagerImpl; import org.apache.cxf.dosgi.dsw.handlers.rest.RsConstants; import org.apache.cxf.dosgi.dsw.handlers.rest.RsProvider; import org.apache.cxf.jaxrs.client.WebClient; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Test; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; public class RsProviderTest { @Test public void testDefaultRest() throws IOException { RsProvider rsProvider = new RsProvider(); HttpServiceManager httpServiceManager = new HttpServiceManager(); Dictionary<String, Object> config = new Hashtable<>(); httpServiceManager.initFromConfig(config); rsProvider.setHttpServiceManager(httpServiceManager); IntentManagerImpl intentManager = new IntentManagerImpl(); rsProvider.setIntentManager(intentManager); TaskServiceImpl taskService = new TaskServiceImpl(); BundleContext callingContext = EasyMock.createMock(BundleContext.class); Map<String, Object> props = new HashMap<>(); props.put(Constants.OBJECTCLASS, new String[]{TaskService.class.getName()}); String serviceAddress = "http://localhost:9181/"; props.put(RsConstants.RS_ADDRESS_PROPERTY, serviceAddress); Class<?>[] ifaces = new Class[]{TaskService.class}; try (Endpoint endpoint = rsProvider.exportService(taskService, callingContext, props, ifaces)) { Assert.assertEquals(serviceAddress, endpoint.description().getId()); Task task1 = WebClient.create(serviceAddress).path("/task").get(Task.class); Assert.assertEquals("test", task1.getName()); TaskService proxy = (TaskService)rsProvider.importEndpoint(TaskService.class.getClassLoader(), callingContext, ifaces, endpoint.description()); Task task = proxy.getTask(); Assert.assertEquals("test", task.getName()); } } }
978
0
Create_ds/cxf-dosgi/provider-rs/src/main/java/org/apache/cxf/dosgi/dsw/handlers
Create_ds/cxf-dosgi/provider-rs/src/main/java/org/apache/cxf/dosgi/dsw/handlers/rest/RsProvider.java
/** * 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.cxf.dosgi.dsw.handlers.rest; import static org.osgi.service.remoteserviceadmin.RemoteConstants.REMOTE_CONFIGS_SUPPORTED; import static org.osgi.service.remoteserviceadmin.RemoteConstants.REMOTE_INTENTS_SUPPORTED; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.apache.aries.rsa.spi.DistributionProvider; import org.apache.aries.rsa.spi.Endpoint; import org.apache.aries.rsa.spi.IntentUnsatisfiedException; import org.apache.cxf.Bus; import org.apache.cxf.binding.BindingConfiguration; import org.apache.cxf.databinding.DataBinding; import org.apache.cxf.dosgi.common.endpoint.ServerEndpoint; import org.apache.cxf.dosgi.common.handlers.BaseDistributionProvider; import org.apache.cxf.dosgi.common.httpservice.HttpServiceManager; import org.apache.cxf.dosgi.common.intent.IntentManager; import org.apache.cxf.dosgi.common.proxy.ProxyFactory; import org.apache.cxf.dosgi.common.util.PropertyHelper; import org.apache.cxf.endpoint.Server; import org.apache.cxf.feature.Feature; import org.apache.cxf.jaxrs.AbstractJAXRSFactoryBean; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean; import org.apache.cxf.jaxrs.ext.ContextProvider; import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; import org.osgi.framework.BundleContext; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.osgi.service.remoteserviceadmin.EndpointDescription; import org.osgi.service.remoteserviceadmin.RemoteConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component(property = // {// REMOTE_CONFIGS_SUPPORTED + "=" + RsConstants.RS_CONFIG_TYPE, REMOTE_INTENTS_SUPPORTED + "=" }) public class RsProvider extends BaseDistributionProvider implements DistributionProvider { private static final Logger LOG = LoggerFactory.getLogger(RsProvider.class); @Reference public void setHttpServiceManager(HttpServiceManager httpServiceManager) { this.httpServiceManager = httpServiceManager; } @Reference public void setIntentManager(IntentManager intentManager) { this.intentManager = intentManager; } @Override public String[] getSupportedTypes() { return new String[] {RsConstants.RS_CONFIG_TYPE}; } @Override @SuppressWarnings("rawtypes") public Object importEndpoint(ClassLoader consumerLoader, BundleContext consumerContext, Class[] interfaces, EndpointDescription endpoint) { if (interfaces.length > 1) { throw new IllegalArgumentException("Multiple interfaces are not supported by this provider"); } Set<String> intentNames = intentManager.getImported(endpoint.getProperties()); List<Object> intents = intentManager.getRequiredIntents(intentNames); Class<?> iClass = interfaces[0]; String address = PropertyHelper.getProperty(endpoint.getProperties(), RsConstants.RS_ADDRESS_PROPERTY); if (address == null) { LOG.warn("Remote address is unavailable"); return null; } return createJaxrsProxy(address, iClass, null, endpoint, intents); } private Object createJaxrsProxy(String address, Class<?> iClass, ClassLoader loader, EndpointDescription endpoint, List<Object> intents) { JAXRSClientFactoryBean factory = new JAXRSClientFactoryBean(); factory.setAddress(address); if (loader != null) { factory.setClassLoader(loader); } addContextProperties(factory, endpoint.getProperties(), RsConstants.RS_CONTEXT_PROPS_PROP_KEY); factory.setServiceClass(iClass); applyIntents(intents, factory); return ProxyFactory.create(factory.create(), iClass); } @Override @SuppressWarnings("rawtypes") public Endpoint exportService(Object serviceBean, BundleContext callingContext, Map<String, Object> endpointProps, Class[] exportedInterfaces) throws IntentUnsatisfiedException { if (!configTypeSupported(endpointProps, RsConstants.RS_CONFIG_TYPE)) { return null; } String contextRoot = PropertyHelper.getProperty(endpointProps, RsConstants.RS_HTTP_SERVICE_CONTEXT); Class<?> iClass = exportedInterfaces[0]; String address = PropertyHelper.getProperty(endpointProps, RsConstants.RS_ADDRESS_PROPERTY); if (address == null) { address = httpServiceManager.getDefaultAddress(iClass); } final Long sid = (Long) endpointProps.get(RemoteConstants.ENDPOINT_SERVICE_ID); Set<String> intentNames = intentManager.getExported(endpointProps); List<Object> intents = intentManager.getRequiredIntents(intentNames); intents.addAll(intentManager.getIntentsFromService(serviceBean)); Bus bus = createBus(sid, callingContext, contextRoot, endpointProps); LOG.info("Creating JAXRS endpoint for " + iClass.getName() + " with address " + address); JAXRSServerFactoryBean factory = createServerFactory(callingContext, endpointProps, iClass, serviceBean, address, bus); applyIntents(intents, factory); String completeEndpointAddress = httpServiceManager.getAbsoluteAddress(contextRoot, address); EndpointDescription epd = createEndpointDesc(endpointProps, // new String[] {RsConstants.RS_CONFIG_TYPE}, completeEndpointAddress, intentNames); return createServerFromFactory(factory, epd); } private void applyIntents(List<Object> intents, AbstractJAXRSFactoryBean factory) { List<Feature> features = intentManager.getIntents(Feature.class, intents); factory.setFeatures(features); DataBinding dataBinding = intentManager.getIntent(DataBinding.class, intents); if (dataBinding != null) { factory.setDataBinding(dataBinding); } BindingConfiguration binding = intentManager.getIntent(BindingConfiguration.class, intents); if (binding != null) { factory.setBindingConfig(binding); } List<Object> providers = new ArrayList<>(); for (Object intent : intents) { if (isProvider(intent)) { providers.add(intent); } } factory.setProviders(providers); } private boolean isProvider(Object intent) { return intent.getClass().getAnnotation(Provider.class) != null // || (intent instanceof ExceptionMapper) // || (intent instanceof MessageBodyReader) // || (intent instanceof MessageBodyWriter) // || (intent instanceof ContextResolver) // || (intent instanceof ContextProvider); } private Endpoint createServerFromFactory(JAXRSServerFactoryBean factory, EndpointDescription epd) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(JAXRSServerFactoryBean.class.getClassLoader()); Server server = factory.create(); return new ServerEndpoint(epd, server); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } } private JAXRSServerFactoryBean createServerFactory(BundleContext callingContext, Map<String, Object> sd, Class<?> iClass, Object serviceBean, String address, Bus bus) { JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean(); factory.setBus(bus); factory.setServiceClass(iClass); factory.setResourceProvider(iClass, new SingletonResourceProvider(serviceBean)); factory.setAddress(address); addContextProperties(factory, sd, RsConstants.RS_CONTEXT_PROPS_PROP_KEY); String location = PropertyHelper.getProperty(sd, RsConstants.RS_WADL_LOCATION); setWadlLocation(callingContext, factory, location); return factory; } private void setWadlLocation(BundleContext callingContext, JAXRSServerFactoryBean factory, String location) { if (location != null) { URL wadlURL = callingContext.getBundle().getResource(location); if (wadlURL != null) { factory.setDocLocation(wadlURL.toString()); } } } protected EndpointDescription createEndpointDesc(Map<String, Object> props, String[] importedConfigs, String address, Collection<String> intents) { return super.createEndpointDesc(props, importedConfigs, RsConstants.RS_ADDRESS_PROPERTY, address, intents); } }
979
0
Create_ds/cxf-dosgi/provider-rs/src/main/java/org/apache/cxf/dosgi/dsw/handlers
Create_ds/cxf-dosgi/provider-rs/src/main/java/org/apache/cxf/dosgi/dsw/handlers/rest/RsConstants.java
/** * 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.cxf.dosgi.dsw.handlers.rest; public final class RsConstants { public static final String RS_CONFIG_TYPE = "org.apache.cxf.rs"; public static final String RS_ADDRESS_PROPERTY = RS_CONFIG_TYPE + ".address"; public static final String RS_HTTP_SERVICE_CONTEXT = RS_CONFIG_TYPE + ".httpservice.context"; public static final String RS_CONTEXT_PROPS_PROP_KEY = RS_CONFIG_TYPE + ".context.properties"; public static final String RS_WADL_LOCATION = RS_CONFIG_TYPE + ".wadl.location"; private RsConstants() { // never constructed } }
980
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/MultiBundleTools.java
/** * 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.cxf.dosgi.itests.multi; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; public final class MultiBundleTools { private MultiBundleTools() { } private static Collection<String> getDistroBundles(File distroDir) { List<String> bundles = new ArrayList<>(); File bundlesDir = new File(distroDir, "bundle"); for (File file : bundlesDir.listFiles()) { if (file.getName().toLowerCase().endsWith(".jar")) { bundles.add(file.toURI().toASCIIString()); } } return bundles; } private static File getRootDirectory() { URL url = MultiBundleTools.class.getResource("/"); // get ${root}/target/test-classes File dir = new File(url.getFile()).getAbsoluteFile(); return dir.getParentFile().getParentFile(); } public static Option getDistro() { File rootDir = getRootDirectory(); File depsDir = new File(rootDir, "target/dependency"); File distroDir = depsDir.listFiles()[0]; Collection<String> bundleUris = getDistroBundles(distroDir); List<Option> opts = new ArrayList<>(); for (String uri : bundleUris) { Option opt = CoreOptions.bundle(uri); // Make sure annotation bundle is loaded first to make sure it is used for resolution if (uri.contains("javax.annotation")) { opts.add(0, opt); } else { opts.add(opt); } } return CoreOptions.composite(opts.toArray(new Option[opts.size()])); } }
981
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/TestExportService.java
/** * 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.cxf.dosgi.itests.multi; import java.net.URL; import java.util.concurrent.Callable; import javax.ws.rs.core.MediaType; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.cxf.dosgi.samples.soap.Task; import org.apache.cxf.dosgi.samples.soap.TaskService; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.zookeeper.ZooKeeper; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Deploys the sample SOAP service and zookeeper discovery. * Then checks the service can be called via plain CXF and is announced in zookeeper */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class TestExportService extends AbstractDosgiTest { private static final String SERVICE_URI = HTTP_BASE_URI + "/cxf/taskservice"; private static final String REST_SERVICE_URI = HTTP_BASE_URI + "/cxf/tasks"; private static final String GREETER_ZOOKEEPER_NODE = // "/osgi/service_registry/http:##localhost:8181#cxf#taskservice"; @Configuration public static Option[] configure() { return new Option[] // {// basicTestOptions(), // configZKServer(), // configZKConsumer(), // taskServiceAPI(), // taskServiceImpl(), // taskRESTAPI(), // taskRESTImpl(), // //debug(), }; } @Test public void testSOAPCall() throws Exception { checkWsdl(new URL(SERVICE_URI + "?wsdl")); TaskService taskService = TaskServiceProxyFactory.create(SERVICE_URI); Task task = taskService.get(1); Assert.assertEquals("Buy some coffee", task.getTitle()); } @Test public void testRESTCall() throws Exception { waitWebPage(REST_SERVICE_URI); final WebClient client = WebClient.create(REST_SERVICE_URI + "/1"); client.accept(MediaType.APPLICATION_XML_TYPE); org.apache.cxf.dosgi.samples.rest.Task task = tryTo("Call REST Resource", new Callable<org.apache.cxf.dosgi.samples.rest.Task>() { @Override public org.apache.cxf.dosgi.samples.rest.Task call() { return client.get(org.apache.cxf.dosgi.samples.rest.Task.class); } } ); Assert.assertEquals("Buy some coffee", task.getTitle()); final WebClient swaggerClient = WebClient.create(REST_SERVICE_URI + "/swagger.json"); String swaggerJson = swaggerClient.get(String.class); Assert.assertEquals("{\"swagger\":\"2.0\"", swaggerJson.substring(0, 16)); } @Test public void testDiscoveryExport() throws Exception { ZooKeeper zk = createZookeeperClient(); assertNodeExists(zk, GREETER_ZOOKEEPER_NODE, 5000); zk.close(); } private void checkWsdl(final URL wsdlURL) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); final DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = tryTo("Parse WSDL", new Callable<Document>() { @Override public Document call() throws Exception { return db.parse(wsdlURL.openStream()); } }); Element el = doc.getDocumentElement(); Assert.assertEquals("definitions", el.getLocalName()); Assert.assertEquals("http://schemas.xmlsoap.org/wsdl/", el.getNamespaceURI()); Assert.assertEquals("TaskServiceService", el.getAttribute("name")); } }
982
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/TaskServiceProxyFactory.java
/** * 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.cxf.dosgi.itests.multi; import org.apache.cxf.dosgi.samples.soap.TaskService; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; public final class TaskServiceProxyFactory { private TaskServiceProxyFactory() { } protected static TaskService create(String serviceUri) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(TaskService.class); factory.setAddress(serviceUri); return (TaskService)factory.create(); } }
983
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/AbstractDosgiTest.java
/** * 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.cxf.dosgi.itests.multi; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.systemPackage; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.newConfiguration; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.util.Collection; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; import javax.inject.Inject; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.junit.Assert; import org.junit.BeforeClass; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.cm.ConfigurationAdminOptions; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.options.extra.VMOption; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceReference; public class AbstractDosgiTest { static final int ZK_PORT = 35101; static final int HTTP_PORT = 8989; static final String HTTP_HOST = "localhost"; // can specify specific bound IP static final String HTTP_BASE_URI = "http://" + HTTP_HOST + ":" + HTTP_PORT; private static final int TIMEOUT = 20; @Inject BundleContext bundleContext; @BeforeClass public static void log() { System.out.println("-----------------------------------------------------------------"); } public <T> T tryTo(String message, Callable<T> func) throws TimeoutException { return tryTo(message, func, 5000); } public <T> T tryTo(String message, Callable<T> func, long timeout) throws TimeoutException { Throwable lastException = null; long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < timeout) { try { T result = func.call(); if (result != null) { return result; } lastException = null; } catch (Throwable e) { lastException = e; } try { Thread.sleep(1000); } catch (InterruptedException e) { continue; } } TimeoutException ex = new TimeoutException("Timeout while trying to " + message); if (lastException != null) { ex.addSuppressed(lastException); } throw ex; } /** * Sleeps for a short interval, throwing an exception if timeout has been reached. Used to facilitate a * retry interval with timeout when used in a loop. * * @param startTime the start time of the entire operation in milliseconds * @param timeout the timeout duration for the entire operation in seconds * @param message the error message to use when timeout occurs * @throws InterruptedException if interrupted while sleeping */ private static void sleepOrTimeout(long startTime, long timeout, String message) throws InterruptedException, TimeoutException { timeout *= 1000; // seconds to millis long elapsed = System.currentTimeMillis() - startTime; long remaining = timeout - elapsed; if (remaining <= 0) { throw new TimeoutException(message); } long interval = Math.min(remaining, 1000); Thread.sleep(interval); } @SuppressWarnings({ "rawtypes", "unchecked" }) protected ServiceReference waitService(BundleContext bc, Class cls, String filter, int timeout) throws Exception { System.out.println("Waiting for service: " + cls + " " + filter); long startTime = System.currentTimeMillis(); while (true) { Collection refs = bc.getServiceReferences(cls, filter); if (refs != null && refs.size() > 0) { return (ServiceReference)refs.iterator().next(); } sleepOrTimeout(startTime, timeout, "Service not found: " + cls + " " + filter); } } protected void waitPort(int port) throws Exception { System.out.println("Waiting for server to appear on port: " + port); long startTime = System.currentTimeMillis(); while (true) { Socket s = null; try { s = new Socket((String)null, port); // yep, its available System.out.println("Port: " + port + " is listening now"); return; } catch (IOException e) { sleepOrTimeout(startTime, TIMEOUT, "Timeout waiting for port " + port); } finally { if (s != null) { try { s.close(); } catch (IOException e) { // ignore } } } } } protected Bundle getBundleByName(BundleContext bc, String name) { for (Bundle bundle : bc.getBundles()) { if (bundle.getSymbolicName().equals(name)) { return bundle; } } return null; } protected static int getFreePort() { try (ServerSocket socket = new ServerSocket()) { socket.setReuseAddress(true); // enables quickly reopening socket on same port socket.bind(new InetSocketAddress(0)); // zero finds a free port return socket.getLocalPort(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } protected void waitWebPage(String urlSt) throws InterruptedException, TimeoutException { System.out.println("Waiting for url " + urlSt); HttpURLConnection con = null; long startTime = System.currentTimeMillis(); while (true) { try { URL url = new URL(urlSt); con = (HttpURLConnection)url.openConnection(); int status = con.getResponseCode(); if (status == 200) { return; } } catch (ConnectException e) { // Ignore connection refused } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { if (con != null) { con.disconnect(); } } sleepOrTimeout(startTime, TIMEOUT, "Timeout waiting for web page " + urlSt); } } protected void assertBundlesStarted() { for (Bundle bundle : bundleContext.getBundles()) { System.out .println(bundle.getSymbolicName() + ":" + bundle.getVersion() + ": " + bundle.getState()); if (bundle.getState() != Bundle.ACTIVE) { try { bundle.start(); } catch (BundleException e) { e.printStackTrace(); } } } } protected ZooKeeper createZookeeperClient() throws Exception { waitPort(ZK_PORT); return new ZooKeeper("localhost:" + ZK_PORT, 1000, null); } protected void assertNodeExists(ZooKeeper zk, String zNode, int timeout) { long endTime = System.currentTimeMillis() + timeout; Stat stat = null; while (stat == null && System.currentTimeMillis() < endTime) { try { stat = zk.exists(zNode, null); Thread.sleep(200); } catch (Exception e) { // Ignore } } Assert.assertNotNull("ZooKeeper node " + zNode + " was not found", stat); } protected static Option configHttpService(String host, int port) { return newConfiguration("org.ops4j.pax.web") .put("org.osgi.service.http.port", "" + port) .put("org.ops4j.pax.web.listening.addresses", host) .asOption(); } protected static Option configZKConsumer() { return newConfiguration("org.apache.aries.rsa.discovery.zookeeper") // .put("zookeeper.host", "127.0.0.1") // .put("zookeeper.port", "" + ZK_PORT).asOption(); } protected static Option configZKServer() { return newConfiguration("org.apache.aries.rsa.discovery.zookeeper.server") .put("clientPort", "" + ZK_PORT) // .asOption(); } protected static Option configLogging() { return ConfigurationAdminOptions.configurationFolder(new File("src/test/resources/cfg")); } protected static MavenArtifactProvisionOption taskServiceAPI() { return mavenBundle().groupId("org.apache.cxf.dosgi.samples") .artifactId("cxf-dosgi-samples-soap-api").versionAsInProject(); } protected static MavenArtifactProvisionOption taskServiceImpl() { return mavenBundle().groupId("org.apache.cxf.dosgi.samples") .artifactId("cxf-dosgi-samples-soap-impl").versionAsInProject(); } protected static MavenArtifactProvisionOption taskRESTAPI() { return mavenBundle().groupId("org.apache.cxf.dosgi.samples") .artifactId("cxf-dosgi-samples-rest-api").versionAsInProject(); } protected static MavenArtifactProvisionOption taskRESTImpl() { return mavenBundle().groupId("org.apache.cxf.dosgi.samples") .artifactId("cxf-dosgi-samples-rest-impl").versionAsInProject(); } protected static Option basicTestOptions() { return composite(CoreOptions.junitBundles(), // MultiBundleTools.getDistro(), // // javax.xml.soap is imported since CXF 3.3.0 (CXF-7872, commit a95593cf), // so we must add it to mutli-bundle distro, but then we get a // conflict with the one exported by framework system bundle (version $JDK) // in this test, and removing a system bundle is a mess, so instead we export // it again with our desired version number so everyone is happy systemPackage("javax.xml.soap;version=1.4.0"), // avoids "ClassNotFoundException: org.glassfish.jersey.internal.RuntimeDelegateImpl" systemProperty("javax.ws.rs.ext.RuntimeDelegate") .value("org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl"), mavenBundle("org.ops4j.pax.tinybundles", "tinybundles").versionAsInProject(), mavenBundle("biz.aQute.bnd", "biz.aQute.bndlib").versionAsInProject(), systemProperty("org.osgi.service.http.port").value("" + HTTP_PORT), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), // systemProperty("pax.exam.osgi.unresolved.fail").value("true"), // systemProperty("org.apache.cxf.stax.allowInsecureParser").value("true"), // systemProperty("rsa.export.policy.filter").value("(name=cxf)"), // configHttpService(HTTP_HOST, HTTP_PORT), configLogging() ); } protected static VMOption debug() { return CoreOptions.vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); } }
984
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/TestExportPolicy.java
/** * 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.cxf.dosgi.itests.multi; import javax.inject.Inject; import org.apache.aries.rsa.spi.ExportPolicy; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.exam.util.Filter; /** * Deploys the sample SOAP service and zookeeper discovery. * Then checks the service can be called via plain CXF and is announced in zookeeper */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class TestExportPolicy extends AbstractDosgiTest { @Inject @Filter("(name=cxf)") ExportPolicy policy; @Configuration public static Option[] configure() { return new Option[] // {// basicTestOptions(), // //debug(), }; } @Test public void testPolicyPresent() { Assert.assertNotNull(policy); } }
985
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/DummyTaskServiceImpl.java
/** * 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.cxf.dosgi.itests.multi; import java.util.Collection; import org.apache.cxf.dosgi.samples.soap.Task; import org.apache.cxf.dosgi.samples.soap.TaskService; public class DummyTaskServiceImpl implements TaskService { @Override public Task get(Integer id) { return new Task(1, "test", ""); } @Override public void addOrUpdate(Task task) { throw new UnsupportedOperationException(); } @Override public void delete(Integer id) { throw new UnsupportedOperationException(); } @Override public Collection<Task> getAll() { throw new UnsupportedOperationException(); } }
986
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/TestImportService.java
/** * 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.cxf.dosgi.itests.multi; import static org.ops4j.pax.exam.CoreOptions.provision; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import java.io.InputStream; import javax.inject.Inject; import org.apache.cxf.dosgi.samples.soap.Task; import org.apache.cxf.dosgi.samples.soap.TaskService; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.tinybundles.core.TinyBundles; import org.osgi.framework.Constants; /** * Creates a service outside OSGi, announces the service via the xml based discovery. Checks that the service * proxy is created by CXF DOSGi and can be called. */ @RunWith(PaxExam.class) public class TestImportService extends AbstractDosgiTest { @Inject TaskService taskService; private Server server; @Configuration public static Option[] configure() { return new Option[] // {// basicTestOptions(), // taskServiceAPI(), // provision(importConfigBundle()), // // increase for debugging systemProperty("org.apache.cxf.dosgi.test.serviceWaitTimeout") .value(System.getProperty("org.apache.cxf.dosgi.test.serviceWaitTimeout", "200")), }; } protected static InputStream importConfigBundle() { return TinyBundles.bundle() // .add("OSGI-INF/remote-service/remote-services.xml", TestImportService.class.getResource("/rs-test1.xml")) // .set(Constants.BUNDLE_SYMBOLICNAME, "importConfig") // .build(TinyBundles.withBnd()); } @Before public void createCXFService() { server = publishService(); } @Test public void testClientConsumer() { Task task = taskService.get(1); Assert.assertEquals("test", task.getTitle()); } @After public void stopCXFService() { server.stop(); } private Server publishService() { System.out.println("Publishing service"); JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean(); factory.setServiceClass(TaskService.class); factory.setAddress("/taskservice"); factory.setServiceBean(new DummyTaskServiceImpl()); return factory.create(); } }
987
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/TestCustomIntent.java
/** * 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.cxf.dosgi.itests.multi; import static org.ops4j.pax.exam.CoreOptions.streamBundle; import java.io.InputStream; import java.util.concurrent.Callable; import org.apache.cxf.dosgi.itests.multi.customintent.ChangeTitleInterceptor; import org.apache.cxf.dosgi.itests.multi.customintent.CustomFeature; import org.apache.cxf.dosgi.itests.multi.customintent.CustomFeatureProvider; import org.apache.cxf.dosgi.itests.multi.customintent.CustomIntentActivator; import org.apache.cxf.dosgi.samples.soap.Task; import org.apache.cxf.dosgi.samples.soap.TaskService; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.tinybundles.core.TinyBundles; import org.osgi.framework.Constants; @RunWith(PaxExam.class) public class TestCustomIntent extends AbstractDosgiTest { @Configuration public static Option[] configure() { return new Option[] // { basicTestOptions(), // taskServiceAPI(), // streamBundle(getCustomIntentBundle()), // //debug() }; } @Test public void testCustomIntent() throws Exception { String serviceUri = HTTP_BASE_URI + "/cxf/taskservice"; final TaskService taskService = TaskServiceProxyFactory.create(serviceUri); Task task = tryTo("Call TaskService", new Callable<Task>() { @Override public Task call() { return taskService.get(1); } }); Assert.assertEquals("changed", task.getTitle()); } private static InputStream getCustomIntentBundle() { return TinyBundles.bundle() // .add(CustomIntentActivator.class) // .add(CustomFeature.class) // .add(CustomFeatureProvider.class) // .add(ChangeTitleInterceptor.class) // .add(DummyTaskServiceImpl.class) // .set(Constants.BUNDLE_SYMBOLICNAME, "CustomIntent") // .set(Constants.BUNDLE_ACTIVATOR, CustomIntentActivator.class.getName()) .build(TinyBundles.withBnd()); } }
988
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/customintent/CustomFeature.java
/** * 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.cxf.dosgi.itests.multi.customintent; import org.apache.cxf.Bus; import org.apache.cxf.feature.AbstractFeature; import org.apache.cxf.interceptor.InterceptorProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class CustomFeature extends AbstractFeature { Logger log = LoggerFactory.getLogger(CustomFeature.class); @Override protected void initializeProvider(InterceptorProvider provider, Bus bus) { log.info("Adding interceptor " + ChangeTitleInterceptor.class.getName()); provider.getOutInterceptors().add(0, new ChangeTitleInterceptor()); super.initializeProvider(provider, bus); } }
989
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/customintent/CustomIntentActivator.java
/** * 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.cxf.dosgi.itests.multi.customintent; import java.util.Dictionary; import java.util.Hashtable; import org.apache.cxf.dosgi.itests.multi.DummyTaskServiceImpl; import org.apache.cxf.dosgi.samples.soap.TaskService; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.service.remoteserviceadmin.RemoteConstants; public class CustomIntentActivator implements BundleActivator { @Override public void start(BundleContext context) { Dictionary<String, String> props = new Hashtable<>(); props.put("org.apache.cxf.dosgi.IntentName", "myIntent"); context.registerService(CustomFeatureProvider.class, new CustomFeatureProvider(), props); Dictionary<String, String> props2 = new Hashtable<>(); props2.put(RemoteConstants.SERVICE_EXPORTED_CONFIGS, "org.apache.cxf.ws"); props2.put("org.apache.cxf.ws.address", "/taskservice"); props2.put(RemoteConstants.SERVICE_EXPORTED_INTERFACES, "*"); props2.put(RemoteConstants.SERVICE_EXPORTED_INTENTS, "myIntent"); context.registerService(TaskService.class, new DummyTaskServiceImpl(), props2); } @Override public void stop(BundleContext context) { } }
990
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/customintent/CustomFeatureProvider.java
/** * 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.cxf.dosgi.itests.multi.customintent; import java.util.Collections; import java.util.List; import org.apache.cxf.dosgi.common.api.IntentsProvider; public class CustomFeatureProvider implements IntentsProvider { @Override public List<?> getIntents() { return Collections.singletonList(new CustomFeature()); } }
991
0
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi
Create_ds/cxf-dosgi/itests/multi-bundle/src/test/java/org/apache/cxf/dosgi/itests/multi/customintent/ChangeTitleInterceptor.java
/** * 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.cxf.dosgi.itests.multi.customintent; import java.lang.reflect.Method; import org.apache.cxf.dosgi.samples.soap.Task; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageContentsList; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class ChangeTitleInterceptor extends AbstractPhaseInterceptor<Message> { Logger log = LoggerFactory.getLogger(ChangeTitleInterceptor.class); ChangeTitleInterceptor() { super(Phase.USER_LOGICAL); } @Override public void handleMessage(Message message) throws Fault { try { MessageContentsList contents = MessageContentsList.getContentsList(message); Object response = contents.get(0); Method method = response.getClass().getMethod("getReturn"); Task task = (Task)method.invoke(response); task.setTitle("changed"); } catch (Exception e) { log.warn("Error in interceptor", e); } } }
992
0
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw/decorator/DecorationParserTest.java
/** * 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.cxf.dosgi.dsw.decorator; import java.io.IOException; import java.net.URL; import java.util.List; import javax.xml.bind.JAXBException; import org.apache.cxf.xmlns.service_decoration._1_0.AddPropertyType; import org.apache.cxf.xmlns.service_decoration._1_0.MatchPropertyType; import org.apache.cxf.xmlns.service_decoration._1_0.MatchType; import org.apache.cxf.xmlns.service_decoration._1_0.ServiceDecorationType; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DecorationParserTest { @Test public void testGetDecoratorForSD() throws JAXBException, IOException { URL resource = getClass().getResource("/test-resources/sd.xml"); List<ServiceDecorationType> elements = new DecorationParser().getDecorations(resource); assertEquals(1, elements.size()); ServiceDecorationType decoration = elements.get(0); assertEquals(1, decoration.getMatch().size()); MatchType match = decoration.getMatch().get(0); assertEquals("org.acme.foo.*", match.getInterface()); assertEquals(1, match.getMatchProperty().size()); MatchPropertyType matchProp = match.getMatchProperty().get(0); assertEquals("test.prop", matchProp.getName()); assertEquals("xyz", matchProp.getValue()); assertEquals(1, match.getAddProperty().size()); AddPropertyType addProp = match.getAddProperty().get(0); assertEquals("test.too", addProp.getName()); assertEquals("ahaha", addProp.getValue()); assertEquals("java.lang.String", addProp.getType()); } @Test public void testGetDecorationForNull() throws JAXBException, IOException { List<ServiceDecorationType> elements = new DecorationParser().getDecorations(null); Assert.assertEquals(0, elements.size()); } }
993
0
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorBundleListenerTest.java
/** * 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.cxf.dosgi.dsw.decorator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.easymock.EasyMock; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import static org.junit.Assert.assertEquals; public class ServiceDecoratorBundleListenerTest { @Test public void testBundleListener() { BundleContext bc = EasyMock.createMock(BundleContext.class); EasyMock.replay(bc); final List<String> called = new ArrayList<>(); ServiceDecoratorImpl serviceDecorator = new ServiceDecoratorImpl() { @Override void addDecorations(Bundle bundle) { called.add("addDecorations"); } @Override void removeDecorations(Bundle bundle) { called.add("removeDecorations"); } }; Bundle b = EasyMock.createMock(Bundle.class); EasyMock.replay(b); ServiceDecoratorBundleListener listener = new ServiceDecoratorBundleListener(serviceDecorator); assertEquals("Precondition failed", 0, called.size()); listener.bundleChanged(new BundleEvent(BundleEvent.INSTALLED, b)); assertEquals(0, called.size()); listener.bundleChanged(new BundleEvent(BundleEvent.STARTED, b)); assertEquals(Arrays.asList("addDecorations"), called); listener.bundleChanged(new BundleEvent(BundleEvent.STOPPING, b)); assertEquals(Arrays.asList("addDecorations", "removeDecorations"), called); } }
994
0
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorImplTest.java
/** * 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.cxf.dosgi.dsw.decorator; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class ServiceDecoratorImplTest { private static final Map<String, Object> EMPTY = new HashMap<>(); private static final URL RES_SD = getResource("/test-resources/sd.xml"); private static final URL RES_SD1 = getResource("/test-resources/sd1.xml"); private static final URL RES_SD2 = getResource("/test-resources/sd2.xml"); private static final URL RES_SD0 = getResource("/test-resources/sd0.xml"); private static final URL RES_SD_1 = getResource("/test-resources/sd-1.xml"); @Test @SuppressWarnings("rawtypes") public void testAddRemoveDecorations() { final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.acme.foo.Bar"}); serviceProps.put("test.prop", "xyz"); Bundle b = createBundleContaining(RES_SD); ServiceDecoratorImpl sd = new ServiceDecoratorImpl(); assertEquals("Precondition failed", 0, sd.decorations.size()); sd.addDecorations(b); assertEquals(1, sd.decorations.size()); Map<String, Object> target = new HashMap<>(); ServiceReference sref = EasyMock.createMock(ServiceReference.class); EasyMock.expect(sref.getProperty((String) EasyMock.anyObject())).andAnswer(new IAnswer<Object>() { @Override public Object answer() { return serviceProps.get(EasyMock.getCurrentArguments()[0]); } }).anyTimes(); EasyMock.replay(sref); sd.decorate(sref, target); Map<String, Object> expected = new HashMap<>(); expected.put("test.too", "ahaha"); assertEquals(expected, target); // remove it again sd.removeDecorations(b); assertEquals(0, sd.decorations.size()); Map<String, Object> target2 = new HashMap<>(); sd.decorate(sref, target2); assertEquals(EMPTY, target2); } @Test public void testAddDecorations() { final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.acme.foo.Bar"}); serviceProps.put("test.prop", "xyz"); Map<String, Object> expected = new HashMap<>(); expected.put("test.too", "ahaha"); assertDecorate(serviceProps, expected, RES_SD); } @Test public void testAddDecorations1() { Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.A"}); Map<String, Object> expected = new HashMap<>(); expected.put("A", "B"); expected.put("C", 2); assertDecorate(serviceProps, expected, RES_SD1, RES_SD2); } @Test public void testAddDecorations2() { Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.D"}); assertDecorate(serviceProps, EMPTY, RES_SD1, RES_SD2); } @Test public void testAddDecorations3() { Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.B"}); serviceProps.put("x", "y"); Map<String, Object> expected = new HashMap<>(); expected.put("bool", Boolean.TRUE); assertDecorate(serviceProps, expected, RES_SD1, RES_SD2); } @Test public void testAddDecorations4() { Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.C"}); serviceProps.put("x", "z"); Map<String, Object> expected = new HashMap<>(); expected.put("bool", Boolean.FALSE); assertDecorate(serviceProps, expected, RES_SD1, RES_SD2); } @Test public void testAddDecorations5() { Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.C"}); serviceProps.put("x", "x"); assertDecorate(serviceProps, EMPTY, RES_SD1, RES_SD2); } @Test public void testAddDecorations6() { Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.D"}); assertDecorate(serviceProps, EMPTY, RES_SD0); } @Test public void testAddDecorations7() { Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.test.D"}); assertDecorate(serviceProps, EMPTY, RES_SD_1); } private void assertDecorate(final Map<String, Object> serviceProps, Map<String, Object> expected, URL... resources) { Map<String, Object> actual = testDecorate(serviceProps, resources); assertEquals(expected, actual); } @SuppressWarnings("rawtypes") private Map<String, Object> testDecorate(final Map<String, Object> serviceProps, URL... resources) { Bundle b = createBundleContaining(resources); ServiceDecoratorImpl sd = new ServiceDecoratorImpl(); sd.addDecorations(b); Map<String, Object> target = new HashMap<>(); ServiceReference sref = EasyMock.createMock(ServiceReference.class); EasyMock.expect(sref.getProperty((String) EasyMock.anyObject())).andAnswer(new IAnswer<Object>() { @Override public Object answer() { return serviceProps.get(EasyMock.getCurrentArguments()[0]); } }).anyTimes(); EasyMock.replay(sref); sd.decorate(sref, target); return target; } private Bundle createBundleContaining(URL... resources) { Bundle b = EasyMock.createMock(Bundle.class); EasyMock.expect(b.findEntries("OSGI-INF/remote-service", "*.xml", false)).andReturn( Collections.enumeration(Arrays.asList(resources))).anyTimes(); EasyMock.expect(b.getSymbolicName()).andReturn("bundlename"); EasyMock.replay(b); return b; } private static URL getResource(String path) { URL resource = ServiceDecoratorImplTest.class.getResource(path); assertNotNull("Resource " + path + " not found!", resource); return resource; } }
995
0
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw
Create_ds/cxf-dosgi/decorator/src/test/java/org/apache/cxf/dosgi/dsw/decorator/InterfaceRuleTest.java
/** * 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.cxf.dosgi.dsw.decorator; import java.util.HashMap; import java.util.Map; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @SuppressWarnings("rawtypes") public class InterfaceRuleTest { @Test public void testDUMMY() { assertTrue(true); } @Test public void testInterfaceRuleGetBundle() { Bundle b = EasyMock.createMock(Bundle.class); EasyMock.replay(b); InterfaceRule ir = new InterfaceRule(b, "org.apache.Foo"); assertSame(b, ir.getBundle()); } @Test public void testInterfaceRule1() { InterfaceRule ir = new InterfaceRule(null, "org.apache.Foo"); ir.addProperty("x", "y", String.class.getName()); final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"a.b.C", "org.apache.Foo"}); ServiceReference sref = mockServiceReference(serviceProps); Map<String, Object> m = new HashMap<>(); m.put("a", "b"); ir.apply(sref, m); Map<String, Object> expected = new HashMap<>(); expected.put("a", "b"); expected.put("x", "y"); assertEquals(expected, m); } @Test public void testInterfaceRule2() { InterfaceRule ir = new InterfaceRule(null, "org.apache.F(.*)"); ir.addPropMatch("boo", "baah"); ir.addProperty("x", "1", Integer.class.getName()); ir.addProperty("aaa.bbb", "true", Boolean.class.getName()); final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put("boo", "baah"); serviceProps.put(Constants.OBJECTCLASS, new String[] {"a.b.C", "org.apache.Foo"}); ServiceReference sref = mockServiceReference(serviceProps); Map<String, Object> m = new HashMap<>(); ir.apply(sref, m); Map<String, Object> expected = new HashMap<>(); expected.put("x", 1); expected.put("aaa.bbb", Boolean.TRUE); assertEquals(expected, m); } @Test public void testInterfaceRule3() { InterfaceRule ir = new InterfaceRule(null, "org.apache.F(.*)"); ir.addProperty("x", "y", String.class.getName()); final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put("boo", "baah"); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Boo"}); ServiceReference sref = mockServiceReference(serviceProps); Map<String, Object> m = new HashMap<>(); ir.apply(sref, m); assertEquals(0, m.size()); } @Test public void testInterfaceRule4() { InterfaceRule ir = new InterfaceRule(null, "org.apache.F(.*)"); ir.addPropMatch("boo", "baah"); ir.addProperty("x", "y", String.class.getName()); final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Foo"}); ServiceReference sref = mockServiceReference(serviceProps); Map<String, Object> m = new HashMap<>(); ir.apply(sref, m); assertEquals(0, m.size()); } @Test public void testInterfaceRule5() { InterfaceRule ir = new InterfaceRule(null, "org.apache.Foo"); ir.addPropMatch("test.int", "42"); ir.addProperty("x", "1", Long.class.getName()); final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put("test.int", 42); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Foo"}); ServiceReference sref = mockServiceReference(serviceProps); Map<String, Object> m = new HashMap<>(); m.put("x", "foo"); m.put("aaa.bbb", Boolean.TRUE); ir.apply(sref, m); Map<String, Object> expected = new HashMap<>(); expected.put("x", 1L); expected.put("aaa.bbb", Boolean.TRUE); assertEquals(expected, m); } @Test public void testInterfaceRule6() { InterfaceRule ir = new InterfaceRule(null, "org.apache.Foo"); ir.addPropMatch("test.int", "42"); ir.addProperty("x", "1", Long.class.getName()); final Map<String, Object> serviceProps = new HashMap<>(); serviceProps.put("test.int", 51); serviceProps.put(Constants.OBJECTCLASS, new String[] {"org.apache.Foo"}); ServiceReference sref = mockServiceReference(serviceProps); Map<String, Object> m = new HashMap<>(); m.put("x", "foo"); m.put("aaa.bbb", Boolean.TRUE); ir.apply(sref, m); Map<String, Object> expected = new HashMap<>(); expected.put("x", "foo"); expected.put("aaa.bbb", Boolean.TRUE); assertEquals(expected, m); } private ServiceReference mockServiceReference(final Map<String, Object> serviceProps) { ServiceReference sref = EasyMock.createMock(ServiceReference.class); EasyMock.expect(sref.getProperty((String) EasyMock.anyObject())).andAnswer(new IAnswer<Object>() { @Override public Object answer() { return serviceProps.get(EasyMock.getCurrentArguments()[0]); } }).anyTimes(); EasyMock.expect(sref.getPropertyKeys()) .andReturn(serviceProps.keySet().toArray(new String[] {})).anyTimes(); EasyMock.replay(sref); return sref; } }
996
0
Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw
Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw/decorator/InterfaceRule.java
/** * 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.cxf.dosgi.dsw.decorator; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InterfaceRule implements Rule { private static final Logger LOG = LoggerFactory.getLogger(InterfaceRule.class); private final Bundle bundle; private final Pattern matchPattern; private final Map<String, String> propMatches = new HashMap<>(); private final Map<String, Object> addProps = new HashMap<>(); public InterfaceRule(Bundle b, String im) { bundle = b; matchPattern = Pattern.compile(im); } public synchronized void addPropMatch(String name, String value) { propMatches.put(name, value); } public synchronized void addProperty(String name, String value, String type) { Object obj = value; if (type != null && !String.class.getName().equals(type)) { try { Class<?> cls = getClass().getClassLoader().loadClass(type); Constructor<?> ctor = cls.getConstructor(String.class); obj = ctor.newInstance(value); } catch (Throwable th) { LOG.warn("Could not handle property '" + name + "' with value '" + value + "' of type: " + type, th); return; } } addProps.put(name, obj); } @Override public synchronized void apply(ServiceReference<?> sref, Map<String, Object> target) { String[] objectClass = (String[]) sref.getProperty(Constants.OBJECTCLASS); boolean matches = false; for (String cls : objectClass) { Matcher m = matchPattern.matcher(cls); if (m.matches()) { for (Map.Entry<String, String> pm : propMatches.entrySet()) { Object value = sref.getProperty(pm.getKey()); if (value == null || !Pattern.matches(pm.getValue(), value.toString())) { return; } } matches = true; break; } } if (!matches) { return; } LOG.info("Adding the following properties to " + sref + ": " + addProps); target.putAll(addProps); } @Override public Bundle getBundle() { return bundle; } }
997
0
Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw
Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecoratorImpl.java
/** * 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.cxf.dosgi.dsw.decorator; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.cxf.xmlns.service_decoration._1_0.AddPropertyType; import org.apache.cxf.xmlns.service_decoration._1_0.MatchPropertyType; import org.apache.cxf.xmlns.service_decoration._1_0.MatchType; import org.apache.cxf.xmlns.service_decoration._1_0.ServiceDecorationType; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ServiceDecoratorImpl implements ServiceDecorator { private static final Logger LOG = LoggerFactory.getLogger(ServiceDecoratorImpl.class); final List<Rule> decorations = new CopyOnWriteArrayList<>(); private DecorationParser parser; public ServiceDecoratorImpl() { parser = new DecorationParser(); } @Override public void decorate(ServiceReference<?> sref, Map<String, Object> target) { for (Rule matcher : decorations) { matcher.apply(sref, target); } } void addDecorations(Bundle bundle) { for (ServiceDecorationType decoration : getDecorationElements(bundle)) { for (MatchType match : decoration.getMatch()) { decorations.add(getRule(bundle, match)); } } } private Rule getRule(Bundle bundle, MatchType match) { InterfaceRule m = new InterfaceRule(bundle, match.getInterface()); for (MatchPropertyType propMatch : match.getMatchProperty()) { m.addPropMatch(propMatch.getName(), propMatch.getValue()); } for (AddPropertyType addProp : match.getAddProperty()) { m.addProperty(addProp.getName(), addProp.getValue(), addProp.getType()); } return m; } List<ServiceDecorationType> getDecorationElements(Bundle bundle) { @SuppressWarnings("rawtypes") Enumeration entries = bundle.findEntries("OSGI-INF/remote-service", "*.xml", false); if (entries == null) { return Collections.emptyList(); } List<ServiceDecorationType> elements = new ArrayList<>(); while (entries.hasMoreElements()) { try { elements.addAll(parser.getDecorations((URL)entries.nextElement())); } catch (Exception e) { LOG.warn("Error parsing remote-service descriptions in bundle" + bundle.getSymbolicName(), e); } } return elements; } void removeDecorations(Bundle bundle) { for (Rule r : decorations) { if (bundle.equals(r.getBundle())) { decorations.remove(r); // the iterator doesn't support 'remove' } } } }
998
0
Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw
Create_ds/cxf-dosgi/decorator/src/main/java/org/apache/cxf/dosgi/dsw/decorator/ServiceDecorator.java
/** * 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.cxf.dosgi.dsw.decorator; import java.util.Map; import org.osgi.framework.ServiceReference; public interface ServiceDecorator { void decorate(ServiceReference<?> sref, Map<String, Object> properties); }
999