Search in sources :

Example 1 with Session

use of io.dekorate.Session in project dekorate by dekorateio.

the class KubernetesSessionListener method onClosed.

@Override
public void onClosed() {
    Session session = getSession();
    Project project = getProject();
    Optional<KubernetesConfig> optionalAppConfig = session.getConfigurationRegistry().get(KubernetesConfig.class);
    Optional<ImageConfiguration> optionalImageConfig = session.getConfigurationRegistry().getImageConfig(BuildServiceFactories.supplierMatches(project));
    if (!optionalAppConfig.isPresent() || !optionalImageConfig.isPresent()) {
        return;
    }
    KubernetesConfig kubernetesConfig = optionalAppConfig.get();
    ResourceRegistry resources = session.getResourceRegistry();
    KubernetesList generated = session.getGeneratedResources().getOrDefault(KUBERNETES, new KubernetesList());
    BuildService buildService = null;
    ImageConfiguration imageConfig = optionalImageConfig.get();
    if (imageConfig.isAutoBuildEnabled() || imageConfig.isAutoPushEnabled() || kubernetesConfig.isAutoDeployEnabled()) {
        try {
            buildService = optionalImageConfig.map(BuildServiceFactories.create(getProject(), generated.getItems())).orElseThrow(() -> new IllegalStateException("No applicable BuildServiceFactory found."));
        } catch (Exception e) {
            BuildServiceFactories.log(project, session.getConfigurationRegistry().getAll(ImageConfiguration.class));
            throw DekorateException.launderThrowable("Failed to lookup BuildService.", e);
        }
    }
    List<ProjectHook> hooks = new ArrayList<>();
    if (kubernetesConfig.isAutoDeployEnabled()) {
        hooks.add(new ResourcesApplyHook(getProject(), KUBERNETES, "kubectl"));
        hooks.add(new ScaleDeploymentHook(getProject(), kubernetesConfig.getName(), 0));
    }
    if (imageConfig.isAutoPushEnabled()) {
        // When deploy is enabled, we scale the Deployment down before push
        // then scale it back up once the image has been successfully pushed
        // This ensure that the pod runs the proper image
        hooks.add(new ImageBuildHook(getProject(), buildService));
        hooks.add(new ImagePushHook(getProject(), buildService));
    } else if (imageConfig.isAutoBuildEnabled() || kubernetesConfig.isAutoDeployEnabled()) {
        hooks.add(new ImageBuildHook(getProject(), buildService));
    }
    if (kubernetesConfig.isAutoDeployEnabled()) {
        hooks.add(new ScaleDeploymentHook(getProject(), kubernetesConfig.getName(), kubernetesConfig.getReplicas()));
    }
    if (!hooks.isEmpty()) {
        OrderedHook hook = OrderedHook.create(hooks.toArray(new ProjectHook[hooks.size()]));
        hook.register();
    }
}
Also used : ProjectHook(io.dekorate.hook.ProjectHook) BuildService(io.dekorate.BuildService) KubernetesConfig(io.dekorate.kubernetes.config.KubernetesConfig) ArrayList(java.util.ArrayList) ResourceRegistry(io.dekorate.ResourceRegistry) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) OrderedHook(io.dekorate.hook.OrderedHook) DekorateException(io.dekorate.DekorateException) WithProject(io.dekorate.WithProject) Project(io.dekorate.project.Project) ResourcesApplyHook(io.dekorate.hook.ResourcesApplyHook) ImageConfiguration(io.dekorate.kubernetes.config.ImageConfiguration) ImageBuildHook(io.dekorate.hook.ImageBuildHook) ScaleDeploymentHook(io.dekorate.kubernetes.hook.ScaleDeploymentHook) ImagePushHook(io.dekorate.hook.ImagePushHook) Session(io.dekorate.Session) WithSession(io.dekorate.WithSession)

Example 2 with Session

use of io.dekorate.Session in project dekorate by dekorateio.

the class KubernetesConfigGeneratorTest method shouldGenerateKubernetesWithoutWritingToFileSystem.

@Test
public void shouldGenerateKubernetesWithoutWritingToFileSystem() throws IOException {
    Path tempDir = Files.createTempDirectory("dekorate");
    WithProject withProject = new WithProject() {
    };
    withProject.setProject(FileProjectFactory.create(new File(".")).withDekorateOutputDir(tempDir.toAbsolutePath().toString()).withDekorateMetaDir(tempDir.toAbsolutePath().toString()));
    SessionWriter writer = new SimpleFileWriter(withProject.getProject(), false);
    Session session = Session.getSession();
    session.setWriter(writer);
    KubernetesConfigGenerator generator = new DefaultKubernetesConfigGenerator(session.getConfigurationRegistry());
    Map<String, Object> map = new HashMap<String, Object>() {

        {
            put(KubernetesConfig.class.getName(), new HashMap<String, Object>() {

                {
                    put("name", "generator-test");
                    put("partOf", "generator-test-group");
                    put("version", "latest");
                    put("replicas", 2);
                    put("ports", new Map[] { new HashMap<String, Object>() {

                        {
                            put("containerPort", 8080);
                            put("name", "HTTP");
                        }
                    } });
                    put("livenessProbe", new HashMap<String, Object>() {

                        {
                            put("httpActionPath", "/health");
                        }
                    });
                }
            });
        }
    };
    generator.addPropertyConfiguration(map);
    final Map<String, String> result = session.close();
    KubernetesList list = session.getGeneratedResources().get("kubernetes");
    assertThat(list).isNotNull();
    assertThat(list.getItems()).filteredOn(i -> "Deployment".equals(i.getKind())).hasOnlyOneElementSatisfying(item -> {
        assertThat(item).isInstanceOfSatisfying(Deployment.class, dep -> {
            assertThat(dep.getSpec()).satisfies(spec -> {
                assertThat(spec.getReplicas()).isEqualTo(2);
                assertThat(spec.getTemplate().getSpec()).satisfies(podSpec -> {
                    assertThat(podSpec.getContainers()).hasOnlyOneElementSatisfying(container -> {
                        assertThat(container.getPorts()).hasOnlyOneElementSatisfying(port -> {
                            assertThat(port.getContainerPort()).isEqualTo(8080);
                            assertThat(port.getName()).isEqualTo("HTTP");
                        });
                        assertThat(container.getLivenessProbe().getHttpGet()).satisfies(httpGetAction -> {
                            assertThat(httpGetAction.getPath()).isEqualTo("/health");
                            assertThat(httpGetAction.getPort().getIntVal()).isEqualTo(8080);
                        });
                    });
                });
            });
        });
    });
    assertThat(tempDir.resolve("kubernetes.json")).doesNotExist();
    assertThat(tempDir.resolve("kubernetes.yml")).doesNotExist();
    assertThat(result).hasSize(5);
}
Also used : Path(java.nio.file.Path) WithProject(io.dekorate.WithProject) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) Files(java.nio.file.Files) SimpleFileWriter(io.dekorate.processor.SimpleFileWriter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) IOException(java.io.IOException) HashMap(java.util.HashMap) File(java.io.File) Test(org.junit.jupiter.api.Test) FileProjectFactory(io.dekorate.project.FileProjectFactory) Session(io.dekorate.Session) Map(java.util.Map) SessionWriter(io.dekorate.SessionWriter) Path(java.nio.file.Path) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) HashMap(java.util.HashMap) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) WithProject(io.dekorate.WithProject) SessionWriter(io.dekorate.SessionWriter) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) SimpleFileWriter(io.dekorate.processor.SimpleFileWriter) Session(io.dekorate.Session) Test(org.junit.jupiter.api.Test)

Example 3 with Session

use of io.dekorate.Session in project dekorate by dekorateio.

the class OpenshiftSessionListener method onClosed.

@Override
public void onClosed() {
    Session session = getSession();
    Project project = getProject();
    // We ned to set the TTCL, becuase the KubenretesClient used in this part of
    // code, needs TTCL so that java.util.ServiceLoader can work.
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    List<ProjectHook> hooks = new ArrayList<>();
    try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        Optional<OpenshiftConfig> optionalAppConfig = session.getConfigurationRegistry().get(OpenshiftConfig.class);
        Optional<ImageConfiguration> optionalImageConfig = session.getConfigurationRegistry().getImageConfig(BuildServiceFactories.supplierMatches(project));
        if (!optionalAppConfig.isPresent() || !optionalImageConfig.isPresent()) {
            return;
        }
        OpenshiftConfig openshiftConfig = optionalAppConfig.get();
        ImageConfiguration imageConfig = optionalImageConfig.get();
        String name = session.getConfigurationRegistry().get(OpenshiftConfig.class).map(c -> c.getName()).orElse(getProject().getBuildInfo().getName());
        BuildService buildService = null;
        boolean s2iEnabled = imageConfig instanceof S2iBuildConfig && ((S2iBuildConfig) imageConfig).isEnabled();
        if (imageConfig.isAutoBuildEnabled() || imageConfig.isAutoPushEnabled() || openshiftConfig.isAutoDeployEnabled()) {
            KubernetesList list = session.getGeneratedResources().get("openshift");
            List<HasMetadata> generated = list != null ? list.getItems() : Collections.emptyList();
            try {
                buildService = optionalImageConfig.map(BuildServiceFactories.create(getProject(), generated)).orElseThrow(() -> new IllegalStateException("No applicable BuildServiceFactory found."));
            } catch (Exception e) {
                BuildServiceFactories.log(project, session.getConfigurationRegistry().getAll(ImageConfiguration.class));
                throw DekorateException.launderThrowable("Failed to lookup BuildService.", e);
            }
            hooks.add(new ImageBuildHook(getProject(), buildService));
        }
        if (imageConfig.isAutoPushEnabled() && !s2iEnabled) {
            hooks.add(new ImagePushHook(getProject(), buildService));
        }
        if (openshiftConfig.isAutoDeployEnabled()) {
            hooks.add(new ResourcesApplyHook(getProject(), OPENSHIFT, "oc"));
        }
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
        if (!hooks.isEmpty()) {
            OrderedHook hook = OrderedHook.create(hooks.toArray(new ProjectHook[hooks.size()]));
            hook.register();
        }
    }
}
Also used : DekorateException(io.dekorate.DekorateException) WithProject(io.dekorate.WithProject) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) ImageBuildHook(io.dekorate.hook.ImageBuildHook) ProjectHook(io.dekorate.hook.ProjectHook) Project(io.dekorate.project.Project) BuildServiceFactories(io.dekorate.BuildServiceFactories) BuildService(io.dekorate.BuildService) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ArrayList(java.util.ArrayList) List(java.util.List) OrderedHook(io.dekorate.hook.OrderedHook) Session(io.dekorate.Session) ResourcesApplyHook(io.dekorate.hook.ResourcesApplyHook) ImageConfiguration(io.dekorate.kubernetes.config.ImageConfiguration) OpenshiftConfig(io.dekorate.openshift.config.OpenshiftConfig) Optional(java.util.Optional) S2iBuildConfig(io.dekorate.s2i.config.S2iBuildConfig) WithSession(io.dekorate.WithSession) ImagePushHook(io.dekorate.hook.ImagePushHook) Collections(java.util.Collections) SessionListener(io.dekorate.SessionListener) S2iBuildConfig(io.dekorate.s2i.config.S2iBuildConfig) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ProjectHook(io.dekorate.hook.ProjectHook) BuildService(io.dekorate.BuildService) ArrayList(java.util.ArrayList) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) OpenshiftConfig(io.dekorate.openshift.config.OpenshiftConfig) OrderedHook(io.dekorate.hook.OrderedHook) DekorateException(io.dekorate.DekorateException) WithProject(io.dekorate.WithProject) Project(io.dekorate.project.Project) ResourcesApplyHook(io.dekorate.hook.ResourcesApplyHook) ImageConfiguration(io.dekorate.kubernetes.config.ImageConfiguration) ImageBuildHook(io.dekorate.hook.ImageBuildHook) ImagePushHook(io.dekorate.hook.ImagePushHook) Session(io.dekorate.Session) WithSession(io.dekorate.WithSession)

Example 4 with Session

use of io.dekorate.Session in project dekorate by dekorateio.

the class OpenshiftManifestGeneratorTest method shouldNotAcceptKubernetesConfig.

@Test
public void shouldNotAcceptKubernetesConfig() {
    Session session = Session.getSession();
    OpenshiftManifestGenerator generator = new OpenshiftManifestGenerator(session.getResourceRegistry(), session.getConfigurationRegistry());
    assertFalse(generator.accepts(BaseConfig.class));
}
Also used : OpenshiftManifestGenerator(io.dekorate.openshift.manifest.OpenshiftManifestGenerator) BaseConfig(io.dekorate.kubernetes.config.BaseConfig) Session(io.dekorate.Session) Test(org.junit.jupiter.api.Test)

Example 5 with Session

use of io.dekorate.Session in project dekorate by dekorateio.

the class OpenshiftManifestGeneratorTest method shouldAcceptOpenshiftConfig.

@Test
public void shouldAcceptOpenshiftConfig() {
    Session session = Session.getSession();
    OpenshiftManifestGenerator generator = new OpenshiftManifestGenerator(session.getResourceRegistry(), session.getConfigurationRegistry());
    assertTrue(generator.accepts(OpenshiftConfig.class));
}
Also used : OpenshiftManifestGenerator(io.dekorate.openshift.manifest.OpenshiftManifestGenerator) EditableOpenshiftConfig(io.dekorate.openshift.config.EditableOpenshiftConfig) OpenshiftConfig(io.dekorate.openshift.config.OpenshiftConfig) Session(io.dekorate.Session) Test(org.junit.jupiter.api.Test)

Aggregations

Session (io.dekorate.Session)29 Test (org.junit.jupiter.api.Test)16 WithProject (io.dekorate.WithProject)8 HashMap (java.util.HashMap)8 KubernetesList (io.fabric8.kubernetes.api.model.KubernetesList)7 WithSession (io.dekorate.WithSession)6 SessionWriter (io.dekorate.SessionWriter)5 SimpleFileWriter (io.dekorate.processor.SimpleFileWriter)5 File (java.io.File)5 Map (java.util.Map)5 BuildService (io.dekorate.BuildService)3 DekorateException (io.dekorate.DekorateException)3 ImageBuildHook (io.dekorate.hook.ImageBuildHook)3 KnativeManifestGenerator (io.dekorate.knative.manifest.KnativeManifestGenerator)3 BaseConfig (io.dekorate.kubernetes.config.BaseConfig)3 ImageConfiguration (io.dekorate.kubernetes.config.ImageConfiguration)3 FileProjectFactory (io.dekorate.project.FileProjectFactory)3 TektonManifestGenerator (io.dekorate.tekton.manifest.TektonManifestGenerator)3 IOException (java.io.IOException)3 Files (java.nio.file.Files)3