Search in sources :

Example 61 with Logger

use of io.fabric8.maven.docker.util.Logger in project fabric8-maven-plugin by fabric8io.

the class SpringBootWatcher method runRemoteSpringApplication.

private void runRemoteSpringApplication(String url) {
    log.info("Running RemoteSpringApplication against endpoint: " + url);
    Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getContext().getProject());
    String remoteSecret = properties.getProperty(DEV_TOOLS_REMOTE_SECRET, System.getProperty(DEV_TOOLS_REMOTE_SECRET));
    if (Strings.isNullOrBlank(remoteSecret)) {
        log.warn("There is no `%s` property defined in your src/main/resources/application.properties. Please add one!", DEV_TOOLS_REMOTE_SECRET);
        throw new IllegalStateException("No " + DEV_TOOLS_REMOTE_SECRET + " property defined in application.properties or system properties");
    }
    ClassLoader classLoader = getClass().getClassLoader();
    if (classLoader instanceof URLClassLoader) {
        URLClassLoader pluginClassLoader = (URLClassLoader) classLoader;
        URLClassLoader projectClassLoader = ClassUtil.createProjectClassLoader(getContext().getProject(), log);
        URLClassLoader[] classLoaders = { projectClassLoader, pluginClassLoader };
        StringBuilder buffer = new StringBuilder("java -cp ");
        int count = 0;
        for (URLClassLoader urlClassLoader : classLoaders) {
            URL[] urLs = urlClassLoader.getURLs();
            for (URL u : urLs) {
                if (count++ > 0) {
                    buffer.append(File.pathSeparator);
                }
                try {
                    URI uri = u.toURI();
                    File file = new File(uri);
                    buffer.append(file.getCanonicalPath());
                } catch (Exception e) {
                    throw new IllegalStateException("Failed to create classpath: " + e, e);
                }
            }
        }
        // Add dev tools to the classpath (the main class is not read from BOOT-INF/lib)
        try {
            File devtools = getSpringBootDevToolsJar(getContext().getProject());
            buffer.append(File.pathSeparator);
            buffer.append(devtools.getCanonicalPath());
        } catch (Exception e) {
            throw new IllegalStateException("Failed to include devtools in the classpath: " + e, e);
        }
        buffer.append(" -Dspring.devtools.remote.secret=");
        buffer.append(remoteSecret);
        buffer.append(" org.springframework.boot.devtools.RemoteSpringApplication ");
        buffer.append(url);
        try {
            String command = buffer.toString();
            log.debug("Running: " + command);
            final Process process = Runtime.getRuntime().exec(command);
            final AtomicBoolean outputEnabled = new AtomicBoolean(true);
            Runtime.getRuntime().addShutdownHook(new Thread("fabric8:watch [spring-boot] shutdown hook") {

                @Override
                public void run() {
                    log.info("Terminating the Spring remote client...");
                    outputEnabled.set(false);
                    process.destroy();
                }
            });
            Logger logger = new PrefixedLogger("Spring-Remote", log);
            Thread stdOutPrinter = startOutputProcessor(logger, process.getInputStream(), false, outputEnabled);
            Thread stdErrPrinter = startOutputProcessor(logger, process.getErrorStream(), true, outputEnabled);
            int status = process.waitFor();
            stdOutPrinter.join();
            stdErrPrinter.join();
            if (status != 0) {
                log.warn("Process returned status: %s", status);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to run RemoteSpringApplication: " + e, e);
        }
    } else {
        throw new IllegalStateException("ClassLoader must be a URLClassLoader but it is: " + classLoader.getClass().getName());
    }
}
Also used : Properties(java.util.Properties) Logger(io.fabric8.maven.docker.util.Logger) PrefixedLogger(io.fabric8.maven.core.util.PrefixedLogger) URI(java.net.URI) URL(java.net.URL) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PrefixedLogger(io.fabric8.maven.core.util.PrefixedLogger) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) File(java.io.File)

Example 62 with Logger

use of io.fabric8.maven.docker.util.Logger in project fabric8 by fabric8io.

the class SessionListener method preprocessEnvironment.

protected void preprocessEnvironment(KubernetesClient client, Controller controller, Configuration configuration, Session session) {
    if (configuration.isUseGoFabric8()) {
        // lets invoke gofabric8 to configure the security and secrets
        Logger logger = session.getLogger();
        Commands.assertCommand(logger, "oc", "project", session.getNamespace());
        Commands.assertCommand(logger, "gofabric8", "deploy", "-y", "--console=false", "--templates=false");
        Commands.assertCommand(logger, "gofabric8", "secrets", "-y");
    }
}
Also used : Logger(io.fabric8.arquillian.kubernetes.log.Logger)

Example 63 with Logger

use of io.fabric8.maven.docker.util.Logger in project fabric8 by fabric8io.

the class SessionListener method loadDependency.

protected void loadDependency(Logger log, List<KubernetesList> kubeConfigs, File file, Controller controller, Configuration configuration, Logger logger, String namespace) throws IOException {
    if (file.isFile()) {
        log.info("Loading file " + file);
        Object content;
        if (file.getName().endsWith(".yaml") || file.getName().endsWith(".yml")) {
            content = loadYaml(file);
        } else {
            content = loadJson(file);
        }
        addConfig(kubeConfigs, content, controller, configuration, log, namespace, file.getPath());
    } else {
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                String name = child.getName().toLowerCase();
                if (name.endsWith(".json") || name.endsWith(".yaml") || name.endsWith(".yml")) {
                    loadDependency(log, kubeConfigs, child, controller, configuration, log, namespace);
                }
            }
        }
    }
}
Also used : Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString) File(java.io.File)

Example 64 with Logger

use of io.fabric8.maven.docker.util.Logger in project fabric8 by fabric8io.

the class SessionListener method start.

public void start(@Observes final Start event, KubernetesClient client, Controller controller, Configuration configuration) throws Exception {
    Objects.requireNonNull(client, "KubernetesClient most not be null!");
    Session session = event.getSession();
    final Logger log = session.getLogger();
    String namespace = session.getNamespace();
    System.setProperty(Constants.KUBERNETES_NAMESPACE, namespace);
    log.status("Using Kubernetes at: " + client.getMasterUrl());
    log.status("Creating kubernetes resources inside namespace: " + namespace);
    log.info("if you use OpenShift then type this switch namespaces:     oc project " + namespace);
    log.info("if you use kubernetes then type this to switch namespaces: kubectl namespace " + namespace);
    clearTestResultDirectories(session);
    controller.setNamespace(namespace);
    controller.setThrowExceptionOnError(true);
    controller.setRecreateMode(true);
    controller.setIgnoreRunningOAuthClients(true);
    if (configuration.isCreateNamespaceForTest()) {
        createNamespace(client, controller, session);
    } else {
        String namespaceToUse = configuration.getNamespace();
        checkNamespace(client, controller, session, configuration);
        updateConfigMapStatus(client, session, Constants.RUNNING_STATUS);
        namespace = namespaceToUse;
        controller.setNamespace(namespace);
    }
    List<KubernetesList> kubeConfigs = new LinkedList<>();
    shutdownHook = new ShutdownHook(client, controller, configuration, session, kubeConfigs);
    Runtime.getRuntime().addShutdownHook(shutdownHook);
    try {
        URL configUrl = configuration.getEnvironmentConfigUrl();
        List<String> dependencies = !configuration.getEnvironmentDependencies().isEmpty() ? configuration.getEnvironmentDependencies() : resolver.resolve(session);
        if (configuration.isEnvironmentInitEnabled()) {
            for (String dependency : dependencies) {
                log.info("Found dependency: " + dependency);
                loadDependency(log, kubeConfigs, dependency, controller, configuration, namespace);
            }
            OpenShiftClient openShiftClient = controller.getOpenShiftClientOrNull();
            if (configUrl == null) {
                // lets try find the default configuration generated by the new fabric8-maven-plugin
                String resourceName = "kubernetes.yml";
                if (openShiftClient != null && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.IMAGE) && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.ROUTE)) {
                    resourceName = "openshift.yml";
                }
                configUrl = findConfigResource("/META-INF/fabric8/" + resourceName);
            }
            if (configUrl != null) {
                log.status("Applying kubernetes configuration from: " + configUrl);
                String configText = readAsString(configUrl);
                Object dto = null;
                String configPath = configUrl.getPath();
                if (configPath.endsWith(".yml") || configPath.endsWith(".yaml")) {
                    dto = loadYaml(configText, KubernetesResource.class);
                } else {
                    dto = loadJson(configText);
                }
                dto = expandTemplate(controller, configuration, log, namespace, configUrl.toString(), dto);
                KubernetesList kubeList = KubernetesHelper.asKubernetesList(dto);
                List<HasMetadata> items = kubeList.getItems();
                kubeConfigs.add(kubeList);
            }
            // Lets also try to load the image stream for the project.
            if (openShiftClient != null && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.IMAGE)) {
                File targetDir = new File(System.getProperty("basedir", ".") + "/target");
                if (targetDir.exists() && targetDir.isDirectory()) {
                    File[] files = targetDir.listFiles();
                    if (files != null) {
                        for (File file : files) {
                            if (file.getName().endsWith("-is.yml")) {
                                loadDependency(log, kubeConfigs, file.toURI().toURL().toString(), controller, configuration, namespace);
                            }
                        }
                    }
                }
            // 
            }
        }
        if (!configuration.isEnvironmentInitEnabled() || applyConfiguration(client, controller, configuration, session, kubeConfigs)) {
            displaySessionStatus(client, session);
        } else {
            throw new IllegalStateException("Failed to apply kubernetes configuration.");
        }
    } catch (Exception e) {
        try {
            cleanupSession(client, controller, configuration, session, kubeConfigs, Constants.ERROR_STATUS);
        } catch (MultiException me) {
            throw e;
        } finally {
            if (shutdownHook != null) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
            }
        }
        throw new RuntimeException(e);
    }
}
Also used : Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString) Logger(io.fabric8.arquillian.kubernetes.log.Logger) URL(java.net.URL) MultiException(io.fabric8.utils.MultiException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) File(java.io.File) MultiException(io.fabric8.utils.MultiException) Util.cleanupSession(io.fabric8.arquillian.utils.Util.cleanupSession)

Example 65 with Logger

use of io.fabric8.maven.docker.util.Logger in project fabric8 by fabric8io.

the class SessionListener method expandTemplate.

protected Object expandTemplate(Controller controller, Configuration configuration, Logger log, String namespace, String sourceName, Object dto) {
    if (dto instanceof Template) {
        Template template = (Template) dto;
        KubernetesHelper.setNamespace(template, namespace);
        String parameterNamePrefix = "";
        overrideTemplateParameters(template, configuration.getProperties(), parameterNamePrefix);
        log.status("Applying template in namespace " + namespace);
        controller.installTemplate(template, sourceName);
        dto = controller.processTemplate(template, sourceName);
        if (dto == null) {
            throw new IllegalArgumentException("Failed to process Template!");
        }
    }
    return dto;
}
Also used : Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString) Template(io.fabric8.openshift.api.model.Template)

Aggregations

Test (org.junit.Test)30 File (java.io.File)11 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)10 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)9 URL (java.net.URL)8 GeneratorContext (io.fabric8.maven.generator.api.GeneratorContext)7 ProcessorConfig (io.fabric8.maven.core.config.ProcessorConfig)6 ResourceValidator (io.fabric8.maven.core.util.validator.ResourceValidator)6 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)6 Logger (io.fabric8.maven.docker.util.Logger)6 Util.readAsString (io.fabric8.arquillian.utils.Util.readAsString)5 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)5 Pod (io.fabric8.kubernetes.api.model.Pod)5 OpenShiftMockServer (io.fabric8.openshift.client.server.mock.OpenShiftMockServer)5 Expectations (mockit.Expectations)5 Logger (io.fabric8.arquillian.kubernetes.log.Logger)4 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)4 BuildService (io.fabric8.maven.core.service.BuildService)4 Fabric8ServiceException (io.fabric8.maven.core.service.Fabric8ServiceException)4