Search in sources :

Example 16 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project fabric8-maven-plugin by fabric8io.

the class ImportMojo method getGogsURL.

private String getGogsURL(KubernetesClient kubernetes, String namespace) throws MojoExecutionException {
    try {
        Endpoints endpoints = kubernetes.endpoints().inNamespace(namespace).withName(ServiceNames.GOGS).get();
        int runningEndpoints = 0;
        if (endpoints != null) {
            List<EndpointSubset> subsets = endpoints.getSubsets();
            for (EndpointSubset subset : subsets) {
                List<EndpointAddress> addresses = subset.getAddresses();
                if (addresses != null) {
                    runningEndpoints += addresses.size();
                }
            }
        }
        if (runningEndpoints == 0) {
            return null;
        }
        log.info("Running %s endpoints of %s in namespace %s", runningEndpoints, ServiceNames.GOGS, namespace);
        return KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GOGS, namespace, "http", true);
    } catch (Exception e) {
        String errorMessage = e.getMessage();
        if (errorMessage.contains(String.format("No service gogs running in namespace %s", namespace))) {
            log.info("Gogs service does not exists, defaulting to GitHub");
            return null;
        } else {
            throw new MojoExecutionException(e.getMessage());
        }
    }
}
Also used : Endpoints(io.fabric8.kubernetes.api.model.Endpoints) EndpointSubset(io.fabric8.kubernetes.api.model.EndpointSubset) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) 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) EndpointAddress(io.fabric8.kubernetes.api.model.EndpointAddress)

Example 17 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project fabric8-maven-plugin by fabric8io.

the class ImportMojo method getSecretGitConfigMap.

private ConfigMap getSecretGitConfigMap(KubernetesClient kubernetes, String namespace, String secretNamespace) {
    ConfigMap configMap = kubernetes.configMaps().inNamespace(secretNamespace).withName(FABRIC8_GIT_APP_SECRETS_CONFIGMAP).get();
    if (configMap == null) {
        Map<String, String> labels = new HashMap<String, String>();
        labels.put("provider", "fabric8");
        Map<String, String> data = new HashMap<>();
        data.put(GOGS_REPO_HOST, createGitSecretName(namespace, GOGS_REPO_HOST));
        configMap = new ConfigMapBuilder().withNewMetadata().withName(FABRIC8_GIT_APP_SECRETS_CONFIGMAP).withLabels(labels).endMetadata().withData(data).build();
        log.info("Creating ConfigMap " + FABRIC8_GIT_APP_SECRETS_CONFIGMAP + " in namespace " + secretNamespace);
        kubernetes.configMaps().inNamespace(secretNamespace).withName(FABRIC8_GIT_APP_SECRETS_CONFIGMAP).create(configMap);
    }
    if (configMap.getData() == null) {
        configMap.setData(new HashMap<String, String>());
    }
    return configMap;
}
Also used : ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) HashMap(java.util.HashMap) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder)

Example 18 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient 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 19 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project fabric8-maven-plugin by fabric8io.

the class SpringBootWatcher method watch.

@Override
public void watch(List<ImageConfiguration> configs, Set<HasMetadata> resources, PlatformMode mode) throws Exception {
    KubernetesClient kubernetes = getContext().getKubernetesClient();
    PodLogService.PodLogServiceContext logContext = new PodLogService.PodLogServiceContext.Builder().log(log).newPodLog(getContext().getNewPodLogger()).oldPodLog(getContext().getOldPodLogger()).build();
    new PodLogService(logContext).tailAppPodsLogs(kubernetes, getContext().getNamespace(), resources, false, null, true, null, false);
    String url = getServiceExposeUrl(kubernetes, resources);
    if (url == null) {
        url = getPortForwardUrl(resources);
    }
    if (url != null) {
        runRemoteSpringApplication(url);
    } else {
        throw new IllegalStateException("Unable to open a channel to the remote pod.");
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) PodLogService(io.fabric8.maven.core.service.PodLogService)

Example 20 with KubernetesClient

use of io.fabric8.kubernetes.client.KubernetesClient in project strimzi by strimzi.

the class ClusterControllerTest method startStop.

/**
 * Does the CC start and then stop a verticle per namespace?
 * @param context
 * @param namespaces
 */
private void startStop(TestContext context, String namespaces) {
    AtomicInteger numWatchers = new AtomicInteger(0);
    KubernetesClient client = mock(KubernetesClient.class);
    MixedOperation mockCms = mock(MixedOperation.class);
    when(client.configMaps()).thenReturn(mockCms);
    List<String> namespaceList = asList(namespaces.split(" *,+ *"));
    for (String namespace : namespaceList) {
        MixedOperation mockNamespacedCms = mock(MixedOperation.class);
        when(mockNamespacedCms.watch(any())).thenAnswer(invo -> {
            numWatchers.incrementAndGet();
            Watch mockWatch = mock(Watch.class);
            doAnswer(invo2 -> {
                ((Watcher) invo.getArgument(0)).onClose(null);
                return null;
            }).when(mockWatch).close();
            return mockWatch;
        });
        when(mockNamespacedCms.withLabels(any())).thenReturn(mockNamespacedCms);
        when(mockCms.inNamespace(namespace)).thenReturn(mockNamespacedCms);
    }
    Async async = context.async();
    Map<String, String> env = new HashMap<>();
    env.put(ClusterControllerConfig.STRIMZI_NAMESPACE, namespaces);
    env.put(ClusterControllerConfig.STRIMZI_CONFIGMAP_LABELS, STRIMZI_IO_KIND_CLUSTER);
    env.put(ClusterControllerConfig.STRIMZI_FULL_RECONCILIATION_INTERVAL_MS, "120000");
    Main.run(vertx, client, true, env).setHandler(ar -> {
        context.assertNull(ar.cause(), "Expected all verticles to start OK");
        async.complete();
    });
    async.await();
    context.assertEquals(namespaceList.size(), vertx.deploymentIDs().size(), "A verticle per namespace");
    List<Async> asyncs = new ArrayList<>();
    for (String deploymentId : vertx.deploymentIDs()) {
        Async async2 = context.async();
        asyncs.add(async2);
        vertx.undeploy(deploymentId, ar -> {
            context.assertNull(ar.cause(), "Didn't expect error when undeploying verticle " + deploymentId);
            async2.complete();
        });
    }
    for (Async async2 : asyncs) {
        async2.await();
    }
    if (numWatchers.get() > namespaceList.size()) {
        context.fail("Looks like there were more watchers than namespaces");
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashMap(java.util.HashMap) Async(io.vertx.ext.unit.Async) Watch(io.fabric8.kubernetes.client.Watch) ArrayList(java.util.ArrayList) Watcher(io.fabric8.kubernetes.client.Watcher) MixedOperation(io.fabric8.kubernetes.client.dsl.MixedOperation)

Aggregations

KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)62 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)40 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)21 HashMap (java.util.HashMap)19 Pod (io.fabric8.kubernetes.api.model.Pod)17 Service (io.fabric8.kubernetes.api.model.Service)16 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)14 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)13 IOException (java.io.IOException)12 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)10 File (java.io.File)10 ArrayList (java.util.ArrayList)9 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)8 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)8 Test (org.junit.Test)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)7 Map (java.util.Map)7 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)7 Controller (io.fabric8.kubernetes.api.Controller)6