Search in sources :

Example 41 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8-maven-plugin by fabric8io.

the class BaseGenerator method addFrom.

/**
 * Add the base image either from configuration or from a given selector
 *
 * @param builder for the build image configuration to add the from to.
 */
protected void addFrom(BuildImageConfiguration.Builder builder) {
    String fromMode = getConfigWithSystemFallbackAndDefault(Config.fromMode, "fabric8.generator.fromMode", getFromModeDefault(context.getMode()));
    String from = getConfigWithSystemFallbackAndDefault(Config.from, "fabric8.generator.from", null);
    if ("docker".equalsIgnoreCase(fromMode)) {
        String fromImage = from;
        if (fromImage == null) {
            fromImage = fromSelector != null ? fromSelector.getFrom() : null;
        }
        builder.from(fromImage);
        log.info("Using Docker image %s as base / builder", fromImage);
    } else if ("istag".equalsIgnoreCase(fromMode)) {
        Map<String, String> fromExt = new HashMap<>();
        if (from != null) {
            ImageName iName = new ImageName(from);
            // user/project is considered to be the namespace
            String tag = iName.getTag();
            if (StringUtils.isBlank(tag)) {
                tag = "latest";
            }
            fromExt.put(OpenShiftBuildStrategy.SourceStrategy.name.key(), iName.getSimpleName() + ":" + tag);
            if (iName.getUser() != null) {
                fromExt.put(OpenShiftBuildStrategy.SourceStrategy.namespace.key(), iName.getUser());
            }
            fromExt.put(OpenShiftBuildStrategy.SourceStrategy.kind.key(), "ImageStreamTag");
        } else {
            fromExt = fromSelector != null ? fromSelector.getImageStreamTagFromExt() : null;
        }
        if (fromExt != null) {
            String namespace = fromExt.get(OpenShiftBuildStrategy.SourceStrategy.namespace.key());
            if (namespace != null) {
                log.info("Using ImageStreamTag '%s' from namespace '%s' as builder image", fromExt.get(OpenShiftBuildStrategy.SourceStrategy.name.key()), namespace);
            } else {
                log.info("Using ImageStreamTag '%s' as builder image", fromExt.get(OpenShiftBuildStrategy.SourceStrategy.name.key()));
            }
            builder.fromExt(fromExt);
        }
    } else {
        throw new IllegalArgumentException(String.format("Invalid 'fromMode' in generator configuration for '%s'", getName()));
    }
}
Also used : ImageName(io.fabric8.maven.docker.util.ImageName) HashMap(java.util.HashMap) Map(java.util.Map)

Example 42 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8-maven-plugin by fabric8io.

the class BaseGeneratorTest method addLatestTagIfSnapshot.

@Test
public void addLatestTagIfSnapshot() {
    new Expectations() {

        {
            ctx.getProject();
            result = project;
            project.getVersion();
            result = "1.2-SNAPSHOT";
        }
    };
    BuildImageConfiguration.Builder builder = new BuildImageConfiguration.Builder();
    BaseGenerator generator = createGenerator(null);
    generator.addLatestTagIfSnapshot(builder);
    ;
    BuildImageConfiguration config = builder.build();
    List<String> tags = config.getTags();
    assertEquals(1, tags.size());
    assertTrue(tags.get(0).endsWith("latest"));
}
Also used : Expectations(mockit.Expectations) BuildImageConfiguration(io.fabric8.maven.docker.config.BuildImageConfiguration) Test(org.junit.Test)

Example 43 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8-maven-plugin by fabric8io.

the class ImportMojo method executeInternal.

@Override
public void executeInternal() throws MojoExecutionException, MojoFailureException {
    if (!basedir.isDirectory() || !basedir.exists()) {
        throw new MojoExecutionException("No directory for base directory: " + basedir);
    }
    // lets check for a git repo
    String gitRemoteURL = null;
    Repository repository = null;
    try {
        repository = GitUtils.findRepository(basedir);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to find local git repository in current directory: " + e, e);
    }
    try {
        gitRemoteURL = GitUtils.getRemoteAsHttpsURL(repository);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to get the current git branch: " + e, e);
    }
    try {
        clusterAccess = new ClusterAccess(this.namespace);
        if (Strings.isNullOrBlank(projectName)) {
            projectName = basedir.getName();
        }
        KubernetesClient kubernetes = clusterAccess.createDefaultClient(log);
        KubernetesResourceUtil.validateKubernetesMasterUrl(kubernetes.getMasterUrl());
        String namespace = clusterAccess.getNamespace();
        OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinsShift(kubernetes, namespace);
        if (gitRemoteURL != null) {
            // lets check we don't already have this project imported
            String branch = repository.getBranch();
            BuildConfig buildConfig = findBuildConfigForGitRepo(openShiftClient, namespace, gitRemoteURL, branch);
            if (buildConfig != null) {
                logBuildConfigLink(kubernetes, namespace, buildConfig, log);
                throw new MojoExecutionException("Project already imported into build " + getName(buildConfig) + " for URI: " + gitRemoteURL + " and branch: " + branch);
            } else {
                Map<String, String> annotations = new HashMap<>();
                annotations.put(Annotations.Builds.GIT_CLONE_URL, gitRemoteURL);
                buildConfig = createBuildConfig(kubernetes, namespace, projectName, gitRemoteURL, annotations);
                openShiftClient.buildConfigs().inNamespace(namespace).create(buildConfig);
                ensureExternalGitSecretsAreSetupFor(kubernetes, namespace, gitRemoteURL);
                logBuildConfigLink(kubernetes, namespace, buildConfig, log);
            }
        } else {
            // lets create an import a new project
            UserDetails userDetails = createGogsUserDetails(kubernetes, namespace);
            userDetails.setBranch(branchName);
            BuildConfigHelper.CreateGitProjectResults createGitProjectResults;
            try {
                createGitProjectResults = BuildConfigHelper.importNewGitProject(kubernetes, userDetails, basedir, namespace, projectName, remoteName, "Importing project from mvn fabric8:import", false);
            } catch (WebApplicationException e) {
                Response response = e.getResponse();
                if (response.getStatus() > 400) {
                    String message = getEntityMessage(response);
                    log.warn("Could not create the git repository: %s %s", e, message);
                    log.warn("Are your username and password correct in the Secret %s/%s?", secretNamespace, gogsSecretName);
                    log.warn("To re-enter your password rerun this command with -Dfabric8.passsword.retry=true");
                    throw new MojoExecutionException("Could not create the git repository. " + "Are your username and password correct in the Secret " + secretNamespace + "/" + gogsSecretName + "?" + e + message, e);
                } else {
                    throw e;
                }
            }
            BuildConfig buildConfig = createGitProjectResults.getBuildConfig();
            openShiftClient.buildConfigs().inNamespace(namespace).create(buildConfig);
            logBuildConfigLink(kubernetes, namespace, buildConfig, log);
        }
    } catch (KubernetesClientException e) {
        KubernetesResourceUtil.handleKubernetesClientException(e, this.log);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) IOException(java.io.IOException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) PrompterException(org.codehaus.plexus.components.interactivity.PrompterException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Response(javax.ws.rs.core.Response) Repository(org.eclipse.jgit.lib.Repository) UserDetails(io.fabric8.project.support.UserDetails) BuildConfigHelper(io.fabric8.project.support.BuildConfigHelper) ClusterAccess(io.fabric8.maven.core.access.ClusterAccess) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) BuildConfigHelper.createBuildConfig(io.fabric8.project.support.BuildConfigHelper.createBuildConfig) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 44 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8-maven-plugin by fabric8io.

the class WatcherManager method watch.

public static void watch(List<ImageConfiguration> ret, Set<HasMetadata> resources, WatcherContext watcherCtx) throws Exception {
    PluginServiceFactory<WatcherContext> pluginFactory = watcherCtx.isUseProjectClasspath() ? new PluginServiceFactory<>(watcherCtx, ClassUtil.createProjectClassLoader(watcherCtx.getProject(), watcherCtx.getLogger())) : new PluginServiceFactory<>(watcherCtx);
    boolean isOpenshift = KubernetesHelper.isOpenShift(watcherCtx.getKubernetesClient());
    PlatformMode mode = isOpenshift ? PlatformMode.openshift : PlatformMode.kubernetes;
    List<Watcher> watchers = pluginFactory.createServiceObjects("META-INF/fabric8/watcher-default", "META-INF/fabric8/fabric8-watcher-default", "META-INF/fabric8/watcher", "META-INF/fabric8-watcher");
    ProcessorConfig config = watcherCtx.getConfig();
    Logger log = watcherCtx.getLogger();
    List<Watcher> usableWatchers = config.prepareProcessors(watchers, "watcher");
    log.verbose("Watchers:");
    Watcher chosen = null;
    for (Watcher watcher : usableWatchers) {
        if (watcher.isApplicable(ret, resources, mode)) {
            if (chosen == null) {
                log.verbose(" - %s [selected]", watcher.getName());
                chosen = watcher;
            } else {
                log.verbose(" - %s", watcher.getName());
            }
        } else {
            log.verbose(" - %s [not applicable]", watcher.getName());
        }
    }
    if (chosen == null) {
        throw new IllegalStateException("No watchers can be used for the current project");
    }
    log.info("Running watcher %s", chosen.getName());
    chosen.watch(ret, resources, mode);
}
Also used : WatcherContext(io.fabric8.maven.watcher.api.WatcherContext) Watcher(io.fabric8.maven.watcher.api.Watcher) PlatformMode(io.fabric8.maven.core.config.PlatformMode) Logger(io.fabric8.maven.docker.util.Logger) ProcessorConfig(io.fabric8.maven.core.config.ProcessorConfig)

Example 45 with Project

use of io.fabric8.openshift.api.model.Project in project fabric8-maven-plugin by fabric8io.

the class EnricherManagerTest method enrichSimple.

@Test
public void enrichSimple() {
    new Expectations() {

        {
            context.getConfig();
            result = new ProcessorConfig(Arrays.asList("fmp-project"), null, new HashMap<String, TreeMap>());
        }
    };
    EnricherManager manager = new EnricherManager(null, context);
    KubernetesListBuilder builder = new KubernetesListBuilder();
    builder.addNewReplicaSetItem().withNewSpec().withNewTemplate().withNewSpec().addNewContainer().withName("test").withImage("busybox").endContainer().endSpec().endTemplate().endSpec().endReplicaSetItem();
    manager.enrich(builder);
    KubernetesList list = builder.build();
    assertEquals(1, list.getItems().size());
    ReplicaSet pod = (ReplicaSet) list.getItems().get(0);
    ObjectMeta metadata = pod.getMetadata();
    assertNotNull(metadata);
    Map<String, String> labels = metadata.getLabels();
    assertNotNull(labels);
    assertEquals("fabric8", labels.get("provider"));
}
Also used : Expectations(mockit.Expectations) ReplicaSet(io.fabric8.kubernetes.api.model.extensions.ReplicaSet) ProcessorConfig(io.fabric8.maven.core.config.ProcessorConfig) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)51 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)29 File (java.io.File)14 Expectations (mockit.Expectations)14 ArrayList (java.util.ArrayList)13 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)11 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)11 ProcessorConfig (io.fabric8.maven.core.config.ProcessorConfig)9 IOException (java.io.IOException)8 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)8 VolumeConfig (io.fabric8.maven.core.config.VolumeConfig)7 GeneratorContext (io.fabric8.maven.generator.api.GeneratorContext)6 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)6 PodTemplateSpec (io.fabric8.kubernetes.api.model.PodTemplateSpec)5 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)5 MojoFailureException (org.apache.maven.plugin.MojoFailureException)5 MavenProject (org.apache.maven.project.MavenProject)5 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)4 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3