Search in sources :

Example 46 with Check

use of io.fabric8.karaf.checks.Check 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 47 with Check

use of io.fabric8.karaf.checks.Check in project fabric8-maven-plugin by fabric8io.

the class BaseBoosterIT method waitTillApplicationPodStarts.

/**
 * This variation is used in order to check for the redeployment scenario, since some
 * annotations are added while making changes in source code, and those are checked so
 * that we are able to differentiate between the redeployed pod and the previously
 * existing pod instance from previous deployment.
 *
 * @param key
 * @param value
 * @throws Exception
 */
protected void waitTillApplicationPodStarts(String key, String value) throws InterruptedException {
    logger.info("Waiting for application pod .... ");
    int nPolls = 0;
    // Keep polling till 5 minutes
    while (nPolls < APPLICATION_POD_WAIT_POLLS) {
        PodList podList = openShiftClient.pods().withLabel("app", testsuiteRepositoryArtifactId).list();
        for (Pod pod : podList.getItems()) {
            logger.info("waitTillApplicationPodStarts(" + key + ", " + value + ") -> Pod : " + pod.getMetadata().getName() + ", STATUS : " + KubernetesHelper.getPodStatus(pod) + ", isPodReady : " + KubernetesHelper.isPodReady(pod));
            if (pod.getMetadata().getAnnotations().containsKey(key)) {
                logger.info(pod.getMetadata().getName() + " is redeployed pod.");
            }
            if (pod.getMetadata().getAnnotations().containsKey(key) && pod.getMetadata().getAnnotations().get(key).equalsIgnoreCase(value) && KubernetesHelper.isPodReady(pod)) {
                logger.info("OK ✓ ... Pod wait over.");
                TimeUnit.SECONDS.sleep(10);
                return;
            }
        }
        nPolls++;
        TimeUnit.SECONDS.sleep(10);
    }
    throw new AssertionError("Pod wait timeout! Could not find application pod for " + testsuiteRepositoryArtifactId);
}
Also used : PodList(io.fabric8.kubernetes.api.model.PodList) Pod(io.fabric8.kubernetes.api.model.Pod)

Example 48 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by fabric8io.

the class KubernetesModelProcessorProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    CompilationTaskFactory compilationTaskFactory = new CompilationTaskFactory(processingEnv);
    Set<TypeElement> processors = new HashSet<>();
    // 1st pass collect classes to compile.
    for (Element element : roundEnv.getElementsAnnotatedWith(KubernetesModelProcessor.class)) {
        processors.add(getClassElement(element));
    }
    if (processors.isEmpty()) {
        return true;
    }
    StringWriter writer = new StringWriter();
    try {
        Callable<Boolean> compileTask = compilationTaskFactory.create(processors, writer);
        if (!compileTask.call()) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to compile provider classes. See output below.");
            printCompileErrors(compilationTaskFactory);
            return false;
        }
    } catch (Exception e) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error to compile provider classes, due to: " + e.getMessage() + ". See output below.");
        return false;
    } finally {
        String output = writer.toString();
        if (Strings.isNullOrBlank(output)) {
            output = "success";
        }
        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Fabric8 model generator compiler output:" + output);
    }
    // 2nd pass generate json.
    for (Element element : roundEnv.getElementsAnnotatedWith(KubernetesModelProcessor.class)) {
        KubernetesModelProcessor annotation = element.getAnnotation(KubernetesModelProcessor.class);
        String kubernetesJsonFileName = annotation.value();
        KubernetesResource json = readJson(kubernetesJsonFileName);
        Builder<? extends KubernetesResource> builder;
        if (json instanceof KubernetesList) {
            builder = new KubernetesListBuilder((KubernetesList) json);
        } else if (json instanceof Template) {
            builder = new TemplateBuilder((Template) json);
        } else if (json != null) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Unknown Kubernetes json type:" + json.getClass());
            return false;
        } else {
            return false;
        }
        try {
            if (element instanceof TypeElement) {
                for (ExecutableElement methodElement : ElementFilter.methodsIn(element.getEnclosedElements())) {
                    TypeElement classElement = getClassElement(element);
                    Class<?> cls = Class.forName(classElement.getQualifiedName().toString());
                    final Object instance = cls.newInstance();
                    final String methodName = methodElement.getSimpleName().toString();
                    if (builder instanceof Visitable) {
                        ((Visitable) builder).accept(new Visitor() {

                            @Override
                            public void visit(Object o) {
                                for (Method m : findMethods(instance, methodName, o.getClass())) {
                                    Named named = m.getAnnotation(Named.class);
                                    if (named != null && !Strings.isNullOrBlank(named.value())) {
                                        String objectName = getName(o);
                                        // If a name has been explicitly specified check if there is a match
                                        if (!named.value().equals(objectName)) {
                                            processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Named method:" + m.getName() + " with name:" + named.value() + " doesn't match: " + objectName + ", ignoring");
                                            return;
                                        }
                                    }
                                    try {
                                        m.invoke(instance, o);
                                    } catch (IllegalAccessException e) {
                                        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error invoking visitor method:" + m.getName() + " on:" + instance + "with argument:" + o);
                                    } catch (InvocationTargetException e) {
                                        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error invoking visitor method:" + m.getName() + " on:" + instance + "with argument:" + o);
                                    }
                                }
                            }
                        });
                    } else {
                        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Json type is not visitable.");
                    }
                }
            }
            json = builder.build();
            generateJson(kubernetesJsonFileName, json);
        } catch (Exception ex) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error creating Kubernetes configuration:" + ex.getMessage());
        }
    }
    return true;
}
Also used : Visitor(io.fabric8.kubernetes.api.builder.Visitor) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) TemplateBuilder(io.fabric8.openshift.api.model.TemplateBuilder) ExecutableElement(javax.lang.model.element.ExecutableElement) Visitable(io.fabric8.kubernetes.api.builder.Visitable) KubernetesModelProcessor(io.fabric8.kubernetes.generator.annotation.KubernetesModelProcessor) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) Template(io.fabric8.openshift.api.model.Template) StringWriter(java.io.StringWriter) KubernetesResource(io.fabric8.kubernetes.api.model.KubernetesResource) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) Named(javax.inject.Named) TypeElement(javax.lang.model.element.TypeElement) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 49 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by fabric8io.

the class Controller method applyProjectRequest.

/**
 * Returns true if the ProjectRequest is created
 */
public boolean applyProjectRequest(ProjectRequest entity) {
    String namespace = getOrCreateMetadata(entity).getName();
    LOG.info("Using project: " + namespace);
    String name = getName(entity);
    Objects.notNull(name, "No name for " + entity);
    OpenShiftClient openshiftClient = getOpenShiftClientOrNull();
    if (openshiftClient == null || !openshiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.PROJECT)) {
        LOG.warn("Cannot check for Project " + namespace + " as not running against OpenShift!");
        return false;
    }
    boolean exists = checkNamespace(name);
    // We may want to be more fine-grained on the phase of the project
    if (!exists) {
        try {
            Object answer = openshiftClient.projectrequests().create(entity);
            logGeneratedEntity("Created ProjectRequest: ", namespace, entity, answer);
            return true;
        } catch (Exception e) {
            onApplyError("Failed to create ProjectRequest: " + name + " due " + e.getMessage(), e);
        }
    }
    return false;
}
Also used : OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) JSONObject(org.json.JSONObject) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) FileNotFoundException(java.io.FileNotFoundException) OpenShiftNotAvailableException(io.fabric8.openshift.client.OpenShiftNotAvailableException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 50 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by fabric8io.

the class Controller method doCreateReplicationController.

protected void doCreateReplicationController(ReplicationController replicationController, String namespace, String sourceName) {
    LOG.info("Creating a ReplicationController from " + sourceName + " namespace " + namespace + " name " + getName(replicationController));
    try {
        // lets check that if secrets are required they exist
        ReplicationControllerSpec spec = replicationController.getSpec();
        if (spec != null) {
            PodTemplateSpec template = spec.getTemplate();
            if (template != null) {
                PodSpec podSpec = template.getSpec();
                validatePodSpec(podSpec, namespace);
            }
        }
        Object answer;
        if (Strings.isNotBlank(namespace)) {
            answer = kubernetesClient.replicationControllers().inNamespace(namespace).create(replicationController);
        } else {
            answer = kubernetesClient.replicationControllers().inNamespace(getNamespace()).create(replicationController);
        }
        logGeneratedEntity("Created ReplicationController: ", namespace, replicationController, answer);
    } catch (Exception e) {
        onApplyError("Failed to create ReplicationController from " + sourceName + ". " + e + ". " + replicationController, e);
    }
}
Also used : PodTemplateSpec(io.fabric8.kubernetes.api.model.PodTemplateSpec) PodSpec(io.fabric8.kubernetes.api.model.PodSpec) JSONObject(org.json.JSONObject) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) FileNotFoundException(java.io.FileNotFoundException) OpenShiftNotAvailableException(io.fabric8.openshift.client.OpenShiftNotAvailableException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ReplicationControllerSpec(io.fabric8.kubernetes.api.model.ReplicationControllerSpec)

Aggregations

Test (org.junit.Test)35 IOException (java.io.IOException)23 File (java.io.File)17 ArrayList (java.util.ArrayList)17 HashMap (java.util.HashMap)15 FabricService (io.fabric8.api.FabricService)11 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)11 Map (java.util.Map)10 Container (io.fabric8.api.Container)9 PatchException (io.fabric8.patch.management.PatchException)9 Expectations (mockit.Expectations)9 Profile (io.fabric8.api.Profile)8 TreeMap (java.util.TreeMap)7 Version (io.fabric8.api.Version)6 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)6 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)6 Check (io.fabric8.karaf.checks.Check)5 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)5 Patch (io.fabric8.patch.management.Patch)5