Search in sources :

Example 61 with Controller

use of io.fabric8.kubernetes.api.Controller in project fabric8 by fabric8io.

the class DeleteBuildConfig method main.

public static void main(String... args) {
    if (args.length < 1) {
        System.out.println("Usage nameOfBuildConfig");
        return;
    }
    try {
        String name = args[0];
        System.out.println("Deleting BuildConfig: " + name);
        KubernetesClient kube = new DefaultKubernetesClient();
        String namespace = kube.getNamespace();
        System.out.println("Using namespace: " + namespace);
        Controller controller = new Controller(kube);
        OpenShiftClient openshift = controller.getOpenShiftClientOrJenkinshift();
        if (openshift == null) {
            System.err.println("Cannot connect to OpenShift or Jenkinshift!");
            return;
        }
        BuildConfig buildConfig = openshift.buildConfigs().withName(name).get();
        if (buildConfig != null) {
            System.out.println("Managed to load BuildConfig with resourceVersion " + KubernetesHelper.getResourceVersion(buildConfig));
        } else {
            System.err.println("Could not find BuildConfig called: " + name);
            return;
        }
        Boolean result = openshift.buildConfigs().withName(name).delete();
        System.out.println("Deleted BuildConfig with name " + name + " result: " + result);
    } catch (Exception e) {
        System.out.println("FAILED: " + e);
        e.printStackTrace();
    }
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient)

Example 62 with Controller

use of io.fabric8.kubernetes.api.Controller in project syndesis by syndesisio.

the class ActivityTrackingControllerTest method testLogsController.

@Test
public void testLogsController() throws IOException {
    final String expectedDBState = resource("logs-controller-db.json").trim();
    final String podLogs = resource("test-pod-x23x.txt");
    try (ActivityTrackingController controller = new ActivityTrackingController(jsondb, dbi, null) {

        @Override
        protected PodList listPods() {
            return new PodListBuilder().addNewItem().withNewMetadata().withName("test-pod-x23x").addToLabels(OpenShiftService.COMPONENT_LABEL, "integration").addToLabels(OpenShiftService.DEPLOYMENT_VERSION_LABEL, "3").addToLabels(OpenShiftService.INTEGRATION_ID_LABEL, "my-integration").endMetadata().withNewStatus().withPhase("Running").endStatus().endItem().build();
        }

        @Override
        protected boolean isPodRunning(String name) {
            return true;
        }

        @Override
        protected void watchLog(String podName, Consumer<InputStream> handler, String sinceTime) throws IOException {
            executor.execute(() -> {
                handler.accept(new ByteArrayInputStream(podLogs.getBytes(StandardCharsets.UTF_8)));
            });
        }
    }) {
        controller.setStartupDelay("0 seconds");
        controller.setRetention("1000000000 days");
        controller.open();
        // Eventually all the log data should make it into the jsondb
        given().await().atMost(20, SECONDS).pollInterval(1, SECONDS).untilAsserted(() -> {
            String db = jsondb.getAsString("/", new GetOptions().prettyPrint(true));
            assertThat(db).isEqualTo(expectedDBState);
        });
    }
}
Also used : PodListBuilder(io.fabric8.kubernetes.api.model.PodListBuilder) Consumer(java.util.function.Consumer) ByteArrayInputStream(java.io.ByteArrayInputStream) GetOptions(io.syndesis.server.jsondb.GetOptions) Test(org.junit.Test)

Example 63 with Controller

use of io.fabric8.kubernetes.api.Controller 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 64 with Controller

use of io.fabric8.kubernetes.api.Controller 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 65 with Controller

use of io.fabric8.kubernetes.api.Controller 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)

Aggregations

Test (org.junit.Test)23 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)16 Controller (io.fabric8.kubernetes.api.Controller)13 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)12 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)12 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)9 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)8 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)8 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)8 Async (io.vertx.ext.unit.Async)8 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)7 Service (io.fabric8.kubernetes.api.model.Service)6 File (java.io.File)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)5 ReplicaSet (io.fabric8.kubernetes.api.model.extensions.ReplicaSet)5 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4