Search in sources :

Example 6 with Exec

use of org.bf2.srs.fleetmanager.it.executor.Exec in project kas-fleetshard by bf2fc6cc711aee1a0c2a.

the class BaseCmdKubeClient method process.

@Override
@SuppressWarnings("unchecked")
public K process(Map<String, String> parameters, String file, Consumer<String> c) {
    List<String> command = command(asList(PROCESS, "-f", file), false);
    command.addAll(parameters.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.toList()));
    ExecResult exec = Exec.builder().throwErrors(true).withCommand(command).exec();
    c.accept(exec.out());
    return (K) this;
}
Also used : ExecResult(org.bf2.test.executor.ExecResult)

Example 7 with Exec

use of org.bf2.srs.fleetmanager.it.executor.Exec in project kas-fleetshard by bf2fc6cc711aee1a0c2a.

the class TestExceptionCallbackListener method storeClusterInfo.

/**
 * Stores cluster specific information in case of failed test in test callback
 *
 * @param cluster
 * @param logPath
 * @throws IOException
 */
private void storeClusterInfo(KubeClusterResource cluster, Path logPath) throws IOException {
    Files.createDirectories(logPath);
    LOGGER.info("Storing cluster info for {}", cluster.kubeClient().client().getConfiguration().getMasterUrl());
    Files.writeString(logPath.resolve("describe_cluster.log"), cluster.cmdKubeClient().exec(false, false, "describe", "nodes").out());
    Files.writeString(logPath.resolve("events.log"), cluster.cmdKubeClient().exec(false, false, "get", "events", "--all-namespaces").out());
    ExecutorService executorService = Executors.newFixedThreadPool(4);
    try {
        KubeClient kubeClient = cluster.kubeClient();
        cluster.kubeClient().client().namespaces().list().getItems().stream().filter(ns -> checkAnnotation(ns, Constants.ORG_BF2_KAFKA_PERFORMANCE_COLLECTPODLOG)).forEach(ns -> {
            try {
                Files.writeString(logPath.resolve(String.format("describe_%s_pods.log", ns.getMetadata().getName())), cluster.cmdKubeClient().exec(false, false, "describe", "pods", "-n", ns.getMetadata().getName()).out());
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
            NonNamespaceOperation<Pod, PodList, PodResource<Pod>> podsOp = kubeClient.client().pods().inNamespace(ns.getMetadata().getName());
            List<Pod> pods = podsOp.list().getItems();
            for (Pod p : pods) {
                try {
                    List<Container> containers = podsOp.withName(p.getMetadata().getName()).get().getSpec().getContainers();
                    for (Container c : containers) {
                        executorService.submit(() -> {
                            Path filePath = logPath.resolve(String.format("%s_%s.log", p.getMetadata().getName(), c.getName()));
                            try {
                                Files.writeString(filePath, podsOp.withName(p.getMetadata().getName()).inContainer(c.getName()).getLog());
                            } catch (IOException e) {
                                LOGGER.warn("Cannot write file {}", filePath, e);
                            }
                        });
                    }
                } catch (Exception ex) {
                    LOGGER.warn("Cannot access logs from pod {} ", p.getMetadata().getName(), ex);
                }
                p.getStatus().getContainerStatuses().stream().filter(cs -> cs.getRestartCount() > 0).forEach(cs -> {
                    executorService.submit(() -> {
                        Path filePath = logPath.resolve(String.format("%s_%s_terminated.log", p.getMetadata().getName(), cs.getName()));
                        try {
                            Files.writeString(filePath, podsOp.withName(p.getMetadata().getName()).inContainer(cs.getName()).terminated().getLog());
                        } catch (IOException e) {
                            LOGGER.warn("Cannot write file {}", filePath, e);
                        }
                    });
                });
            }
        });
    } finally {
        executorService.shutdown();
        try {
            executorService.awaitTermination(1, TimeUnit.HOURS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
Also used : Container(io.fabric8.kubernetes.api.model.Container) Files(java.nio.file.Files) Constants(org.bf2.performance.Constants) LifecycleMethodExecutionExceptionHandler(org.junit.jupiter.api.extension.LifecycleMethodExecutionExceptionHandler) Pod(io.fabric8.kubernetes.api.model.Pod) IOException(java.io.IOException) AfterTestExecutionCallback(org.junit.jupiter.api.extension.AfterTestExecutionCallback) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) Collectors(java.util.stream.Collectors) PodResource(io.fabric8.kubernetes.client.dsl.PodResource) Executors(java.util.concurrent.Executors) UncheckedIOException(java.io.UncheckedIOException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) Logger(org.apache.logging.log4j.Logger) KubeClient(org.bf2.test.k8s.KubeClient) PodList(io.fabric8.kubernetes.api.model.PodList) LogManager(org.apache.logging.log4j.LogManager) TestExecutionExceptionHandler(org.junit.jupiter.api.extension.TestExecutionExceptionHandler) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) Path(java.nio.file.Path) PodList(io.fabric8.kubernetes.api.model.PodList) PodResource(io.fabric8.kubernetes.client.dsl.PodResource) Pod(io.fabric8.kubernetes.api.model.Pod) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Container(io.fabric8.kubernetes.api.model.Container) KubeClient(org.bf2.test.k8s.KubeClient) ExecutorService(java.util.concurrent.ExecutorService)

Example 8 with Exec

use of org.bf2.srs.fleetmanager.it.executor.Exec in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class TestInfraManager method runFleetManager.

private void runFleetManager(Map<String, String> appEnv, String nameSuffix, int port) throws IOException {
    appEnv.put("QUARKUS_HTTP_PORT", String.valueOf(port));
    String path = getFleetManagerJarPath();
    Exec executor = new Exec();
    LOGGER.info("Starting srs-fleet-manager app from: {}", path);
    CompletableFuture.supplyAsync(() -> {
        try {
            List<String> cmd = new ArrayList<>();
            cmd.add("java");
            cmd.addAll(Arrays.asList("-jar", path));
            int timeout = executor.execute(cmd, appEnv);
            return timeout == 0;
        } catch (Exception e) {
            LOGGER.error("Failed to start fleet manager (could not find runner JAR).", e);
            System.exit(1);
            return false;
        }
    }, runnable -> new Thread(runnable).start());
    processes.add(new TestInfraProcess() {

        @Override
        public String getName() {
            return "fleet-manager-" + nameSuffix;
        }

        @Override
        public void close() throws Exception {
            executor.stop();
        }

        @Override
        public String getStdOut() {
            return executor.stdOut();
        }

        @Override
        public String getStdErr() {
            return executor.stdErr();
        }

        @Override
        public boolean isContainer() {
            return false;
        }
    });
    try {
        Awaitility.await("fleet manager is reachable on port " + port).atMost(90, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> HttpUtils.isReachable("localhost", port, "fleet manager"));
        Awaitility.await("fleet manager is ready on port " + port).atMost(90, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> HttpUtils.isReady("http://localhost:" + port, "/q/health/ready", false, "fleet manager"));
    } catch (ConditionTimeoutException ex) {
        for (String s : executor.stdOut().split("\n")) {
            LOGGER.info("[STDOUT] {}", s);
        }
        for (String s : executor.stdErr().split("\n")) {
            LOGGER.info("[STDERR] {}", s);
        }
        throw ex;
    }
}
Also used : Exec(org.bf2.srs.fleetmanager.it.executor.Exec) ArrayList(java.util.ArrayList) ConditionTimeoutException(org.awaitility.core.ConditionTimeoutException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ConditionTimeoutException(org.awaitility.core.ConditionTimeoutException) UncheckedIOException(java.io.UncheckedIOException)

Example 9 with Exec

use of org.bf2.srs.fleetmanager.it.executor.Exec in project srs-fleet-manager by bf2fc6cc711aee1a0c2a.

the class TestInfraManager method runTenantManager.

// TODO replace tenant manager with mock?
private void runTenantManager(boolean authEnabled) throws IOException {
    Map<String, String> appEnv = new HashMap<>();
    if (authEnabled) {
        appEnv.put("AUTH_ENABLED", "true");
        appEnv.put("KEYCLOAK_URL", getMandatoryEnvVar(MAS_SSO_URL));
        appEnv.put("KEYCLOAK_REALM", getMandatoryEnvVar(MAS_SSO_REALM));
        appEnv.put("KEYCLOAK_API_CLIENT_ID", getMandatoryEnvVar(MAS_SSO_CLIENT_ID));
    }
    String datasourceUrl = deployPostgresql("tenant-manager");
    appEnv.put("DATASOURCE_URL", datasourceUrl);
    appEnv.put("DATASOURCE_USERNAME", "postgres");
    appEnv.put("DATASOURCE_PASSWORD", "postgres");
    // registry is not deployed in purpose, it may still work
    appEnv.put("REGISTRY_ROUTE_URL", "http://localhost:3888");
    appEnv.put("LOG_LEVEL", "DEBUG");
    String path = getTenantManagerJarPath();
    LOGGER.info("Starting Tenant Manager app from: {}", path);
    Exec executor = new Exec();
    CompletableFuture.supplyAsync(() -> {
        try {
            List<String> cmd = new ArrayList<>();
            cmd.add("java");
            cmd.addAll(Arrays.asList("-jar", path));
            int timeout = executor.execute(cmd, appEnv);
            return timeout == 0;
        } catch (Exception e) {
            LOGGER.error("Failed to start tenant manager (could not find runner JAR).", e);
            System.exit(1);
            return false;
        }
    }, runnable -> new Thread(runnable).start());
    processes.add(new TestInfraProcess() {

        @Override
        public String getName() {
            return "tenant-manager";
        }

        @Override
        public void close() throws Exception {
            executor.stop();
        }

        @Override
        public String getStdOut() {
            return executor.stdOut();
        }

        @Override
        public String getStdErr() {
            return executor.stdErr();
        }

        @Override
        public boolean isContainer() {
            return false;
        }
    });
    Awaitility.await("Tenant Manager is reachable").atMost(45, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> HttpUtils.isReachable("localhost", 8585, "Tenant Manager"));
    Awaitility.await("Tenant Manager is ready").atMost(45, TimeUnit.SECONDS).pollInterval(1, TimeUnit.SECONDS).until(() -> HttpUtils.isReady(this.tenantManagerUrl, "/q/health/ready", false, "Tenant Manager"));
}
Also used : Exec(org.bf2.srs.fleetmanager.it.executor.Exec) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ConditionTimeoutException(org.awaitility.core.ConditionTimeoutException) UncheckedIOException(java.io.UncheckedIOException)

Aggregations

IOException (java.io.IOException)5 UncheckedIOException (java.io.UncheckedIOException)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ArrayList (java.util.ArrayList)2 ConditionTimeoutException (org.awaitility.core.ConditionTimeoutException)2 Exec (org.bf2.srs.fleetmanager.it.executor.Exec)2 ExecBuilder (org.bf2.test.executor.ExecBuilder)2 ExecResult (org.bf2.test.executor.ExecResult)2 KubeClient (org.bf2.test.k8s.KubeClient)2 Container (io.fabric8.kubernetes.api.model.Container)1 Pod (io.fabric8.kubernetes.api.model.Pod)1 PodList (io.fabric8.kubernetes.api.model.PodList)1 NonNamespaceOperation (io.fabric8.kubernetes.client.dsl.NonNamespaceOperation)1 PodResource (io.fabric8.kubernetes.client.dsl.PodResource)1 Route (io.fabric8.openshift.api.model.Route)1 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 HashMap (java.util.HashMap)1 List (java.util.List)1