Search in sources :

Example 36 with Deployment

use of io.fabric8.kubernetes.api.model.apps.Deployment in project fabric8 by jboss-fuse.

the class ContainerUpgradeAndRollbackTest method deployment.

@Deployment
@StartLevelAware(autostart = true)
public static Archive<?> deployment() {
    final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "container-upgrade-rollback-test.jar");
    archive.addPackage(CommandSupport.class.getPackage());
    archive.setManifest(new Asset() {

        @Override
        public InputStream openStream() {
            OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance();
            builder.addBundleManifestVersion(2);
            builder.addBundleSymbolicName(archive.getName());
            builder.addBundleVersion("1.0.0");
            builder.addImportPackages(ServiceLocator.class, FabricService.class);
            builder.addImportPackages("io.fabric8.git");
            builder.addImportPackages(AbstractCommand.class, Action.class);
            builder.addImportPackage("org.apache.felix.service.command;status=provisional");
            builder.addImportPackages(ConfigurationAdmin.class, ServiceTracker.class, Logger.class);
            return builder.openStream();
        }
    });
    return archive;
}
Also used : Action(org.apache.felix.gogo.commands.Action) ServiceTracker(org.osgi.util.tracker.ServiceTracker) InputStream(java.io.InputStream) AbstractCommand(org.apache.felix.gogo.commands.basic.AbstractCommand) Logger(org.slf4j.Logger) JavaArchive(org.jboss.shrinkwrap.api.spec.JavaArchive) ServiceLocator(io.fabric8.api.gravia.ServiceLocator) FabricService(io.fabric8.api.FabricService) OSGiManifestBuilder(org.jboss.osgi.metadata.OSGiManifestBuilder) Asset(org.jboss.shrinkwrap.api.asset.Asset) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) CommandSupport(io.fabric8.itests.support.CommandSupport) StartLevelAware(org.jboss.arquillian.osgi.StartLevelAware) Deployment(org.jboss.arquillian.container.test.api.Deployment)

Example 37 with Deployment

use of io.fabric8.kubernetes.api.model.apps.Deployment in project fabric8 by jboss-fuse.

the class FabricTestSupport method containerSetProfile.

/**
 * Cleans a containers profile by switching to default profile and resetting the profile.
 */
private boolean containerSetProfile(FabricService fabricService, CuratorFramework curator, String containerName, String profileName, Boolean waitForProvision) throws Exception {
    System.out.println("Switching profile: " + profileName + " on container:" + containerName);
    Container container = fabricService.getContainer(containerName);
    Version version = container.getVersion();
    Profile[] profiles = new Profile[] { version.getRequiredProfile(profileName) };
    Profile[] currentProfiles = container.getProfiles();
    Arrays.sort(profiles);
    Arrays.sort(currentProfiles);
    boolean same = true;
    if (profiles.length != currentProfiles.length) {
        same = false;
    } else {
        for (int i = 0; i < currentProfiles.length; i++) {
            if (!currentProfiles[i].equals(profiles[i])) {
                same = false;
            }
        }
    }
    if (!same && waitForProvision) {
        // This is required so that waitForProvisionSuccess doesn't retrun before the deployment agent kicks in.
        ZooKeeperUtils.setData(curator, ZkPath.CONTAINER_PROVISION_RESULT.getPath(containerName), "switching profile");
        container.setProfiles(profiles);
        Provision.containersStatus(Arrays.asList(container), "success", PROVISION_TIMEOUT);
    }
    return same;
}
Also used : Container(io.fabric8.api.Container) Version(io.fabric8.api.Version) Profile(io.fabric8.api.Profile)

Example 38 with Deployment

use of io.fabric8.kubernetes.api.model.apps.Deployment in project fabric8 by jboss-fuse.

the class Controller method applyEntity.

/**
 * Applies the given DTOs onto the Kubernetes master
 */
public void applyEntity(Object dto, String sourceName) throws Exception {
    if (dto instanceof Pod) {
        applyPod((Pod) dto, sourceName);
    } else if (dto instanceof ReplicationController) {
        applyReplicationController((ReplicationController) dto, sourceName);
    } else if (dto instanceof Service) {
        applyService((Service) dto, sourceName);
    } else if (dto instanceof Namespace) {
        applyNamespace((Namespace) dto);
    } else if (dto instanceof Route) {
        applyRoute((Route) dto, sourceName);
    } else if (dto instanceof BuildConfig) {
        applyBuildConfig((BuildConfig) dto, sourceName);
    } else if (dto instanceof DeploymentConfig) {
        DeploymentConfig resource = (DeploymentConfig) dto;
        OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
        if (openShiftClient != null && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.APPS)) {
            applyResource(resource, sourceName, openShiftClient.deploymentConfigs());
        } else {
            LOG.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
        }
    } else if (dto instanceof PolicyBinding) {
        applyPolicyBinding((PolicyBinding) dto, sourceName);
    } else if (dto instanceof RoleBinding) {
        applyRoleBinding((RoleBinding) dto, sourceName);
    } else if (dto instanceof Role) {
        Role resource = (Role) dto;
        OpenShiftClient openShiftClient = getOpenShiftClientOrNull();
        if (openShiftClient != null && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.AUTHORIZATION)) {
            applyResource(resource, sourceName, openShiftClient.roles());
        } else {
            LOG.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
        }
    } else if (dto instanceof ImageStream) {
        applyImageStream((ImageStream) dto, sourceName);
    } else if (dto instanceof OAuthClient) {
        applyOAuthClient((OAuthClient) dto, sourceName);
    } else if (dto instanceof Template) {
        applyTemplate((Template) dto, sourceName);
    } else if (dto instanceof ServiceAccount) {
        applyServiceAccount((ServiceAccount) dto, sourceName);
    } else if (dto instanceof Secret) {
        applySecret((Secret) dto, sourceName);
    } else if (dto instanceof ConfigMap) {
        applyResource((ConfigMap) dto, sourceName, kubernetesClient.configMaps());
    } else if (dto instanceof DaemonSet) {
        applyResource((DaemonSet) dto, sourceName, kubernetesClient.extensions().daemonSets());
    } else if (dto instanceof Deployment) {
        applyResource((Deployment) dto, sourceName, kubernetesClient.extensions().deployments());
    } else if (dto instanceof ReplicaSet) {
        applyResource((ReplicaSet) dto, sourceName, kubernetesClient.extensions().replicaSets());
    } else if (dto instanceof StatefulSet) {
        applyResource((StatefulSet) dto, sourceName, kubernetesClient.apps().statefulSets());
    } else if (dto instanceof Ingress) {
        applyResource((Ingress) dto, sourceName, kubernetesClient.extensions().ingresses());
    } else if (dto instanceof PersistentVolumeClaim) {
        applyPersistentVolumeClaim((PersistentVolumeClaim) dto, sourceName);
    } else if (dto instanceof HasMetadata) {
        HasMetadata entity = (HasMetadata) dto;
        try {
            String namespace = getNamespace();
            String resourceNamespace = getNamespace(entity);
            if (Strings.isNotBlank(namespace) && Strings.isNullOrBlank(resourceNamespace)) {
                getOrCreateMetadata(entity).setNamespace(namespace);
            }
            LOG.info("Applying " + getKind(entity) + " " + getName(entity) + " from " + sourceName);
            kubernetesClient.resource(entity).inNamespace(namespace).createOrReplace();
        } catch (Exception e) {
            onApplyError("Failed to create " + getKind(entity) + " from " + sourceName + ". " + e, e);
        }
    } else {
        throw new IllegalArgumentException("Unknown entity type " + dto);
    }
}
Also used : ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) OAuthClient(io.fabric8.openshift.api.model.OAuthClient) DoneableImageStream(io.fabric8.openshift.api.model.DoneableImageStream) ImageStream(io.fabric8.openshift.api.model.ImageStream) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) Template(io.fabric8.openshift.api.model.Template) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) RoleBinding(io.fabric8.openshift.api.model.RoleBinding) ReplicaSet(io.fabric8.kubernetes.api.model.extensions.ReplicaSet) Route(io.fabric8.openshift.api.model.Route) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Pod(io.fabric8.kubernetes.api.model.Pod) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Service(io.fabric8.kubernetes.api.model.Service) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) Namespace(io.fabric8.kubernetes.api.model.Namespace) PolicyBinding(io.fabric8.openshift.api.model.PolicyBinding) 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) Role(io.fabric8.openshift.api.model.Role) Secret(io.fabric8.kubernetes.api.model.Secret) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) DaemonSet(io.fabric8.kubernetes.api.model.extensions.DaemonSet) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) StatefulSet(io.fabric8.kubernetes.api.model.extensions.StatefulSet)

Example 39 with Deployment

use of io.fabric8.kubernetes.api.model.apps.Deployment in project fabric8 by jboss-fuse.

the class SessionListener method applyConfiguration.

private boolean applyConfiguration(KubernetesClient client, Controller controller, Configuration configuration, Session session, List<KubernetesList> kubeConfigs) throws Exception {
    Logger log = session.getLogger();
    Map<Integer, Callable<Boolean>> conditions = new TreeMap<>();
    Callable<Boolean> sessionPodsReady = new SessionPodsAreReady(client, session);
    Callable<Boolean> servicesReady = new SessionServicesAreReady(client, session, configuration);
    Set<HasMetadata> entities = new TreeSet<>(new HasMetadataComparator());
    for (KubernetesList c : kubeConfigs) {
        entities.addAll(enhance(session, configuration, c).getItems());
    }
    if (containsImageStreamResources(entities)) {
    // no need to use a local image registry
    // as we are using OpenShift and
    } else {
        String registry = getLocalDockerRegistry();
        if (Strings.isNotBlank(registry)) {
            log.status("Adapting resources to pull images from registry: " + registry);
            addRegistryToImageNameIfNotPresent(entities, registry);
        } else {
            log.status("No local fabric8 docker registry found");
        }
    }
    List<Object> items = new ArrayList<>();
    items.addAll(entities);
    // Ensure services are processed first.
    Collections.sort(items, new Comparator<Object>() {

        @Override
        public int compare(Object left, Object right) {
            if (left instanceof Service) {
                return -1;
            } else if (right instanceof Service) {
                return 1;
            } else {
                return 0;
            }
        }
    });
    boolean isOpenshift = client.isAdaptable(OpenShiftClient.class);
    String namespace = session.getNamespace();
    String routeDomain = null;
    if (Strings.isNotBlank(configuration.getKubernetesDomain())) {
        routeDomain = configuration.getKubernetesDomain();
    }
    preprocessEnvironment(client, controller, configuration, session);
    Set<HasMetadata> extraEntities = new TreeSet<>(new HasMetadataComparator());
    for (Object entity : items) {
        if (entity instanceof Pod) {
            Pod pod = (Pod) entity;
            log.status("Applying pod:" + getName(pod));
            Set<Secret> secrets = generateSecrets(client, session, pod.getMetadata());
            String serviceAccountName = pod.getSpec().getServiceAccountName();
            if (Strings.isNotBlank(serviceAccountName)) {
                generateServiceAccount(client, session, secrets, serviceAccountName);
            }
            controller.applyPod(pod, session.getId());
            conditions.put(1, sessionPodsReady);
        } else if (entity instanceof Service) {
            Service service = (Service) entity;
            String serviceName = getName(service);
            log.status("Applying service:" + serviceName);
            controller.applyService(service, session.getId());
            conditions.put(2, servicesReady);
            if (isOpenshift) {
                Route route = Routes.createRouteForService(routeDomain, namespace, service, log);
                if (route != null) {
                    log.status("Applying route for:" + serviceName);
                    controller.applyRoute(route, "route for " + serviceName);
                    extraEntities.add(route);
                }
            }
        } else if (entity instanceof ReplicationController) {
            ReplicationController replicationController = (ReplicationController) entity;
            log.status("Applying replication controller:" + getName(replicationController));
            Set<Secret> secrets = generateSecrets(client, session, replicationController.getSpec().getTemplate().getMetadata());
            String serviceAccountName = replicationController.getSpec().getTemplate().getSpec().getServiceAccountName();
            if (Strings.isNotBlank(serviceAccountName)) {
                generateServiceAccount(client, session, secrets, serviceAccountName);
            }
            controller.applyReplicationController(replicationController, session.getId());
            conditions.put(1, sessionPodsReady);
        } else if (entity instanceof ReplicaSet || entity instanceof Deployment || entity instanceof DeploymentConfig) {
            log.status("Applying " + entity.getClass().getSimpleName() + ".");
            controller.apply(entity, session.getId());
            conditions.put(1, sessionPodsReady);
        } else if (entity instanceof OAuthClient) {
            OAuthClient oc = (OAuthClient) entity;
            // these are global so lets create a custom one for the new namespace
            ObjectMeta metadata = KubernetesHelper.getOrCreateMetadata(oc);
            String name = metadata.getName();
            if (isOpenshift) {
                OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);
                OAuthClient current = openShiftClient.oAuthClients().withName(name).get();
                boolean create = false;
                if (current == null) {
                    current = oc;
                    create = true;
                }
                boolean updated = false;
                // lets add a new redirect entry
                List<String> redirectURIs = current.getRedirectURIs();
                String namespaceSuffix = "-" + namespace;
                String redirectUri = "http://" + name + namespaceSuffix;
                if (Strings.isNotBlank(routeDomain)) {
                    redirectUri += "." + Strings.stripPrefix(routeDomain, ".");
                }
                if (!redirectURIs.contains(redirectUri)) {
                    redirectURIs.add(redirectUri);
                    updated = true;
                }
                current.setRedirectURIs(redirectURIs);
                log.status("Applying OAuthClient:" + name);
                controller.setSupportOAuthClients(true);
                if (create) {
                    openShiftClient.oAuthClients().create(current);
                } else {
                    if (updated) {
                        // TODO this should work!
                        // openShiftClient.oAuthClients().withName(name).replace(current);
                        openShiftClient.oAuthClients().withName(name).delete();
                        current.getMetadata().setResourceVersion(null);
                        openShiftClient.oAuthClients().create(current);
                    }
                }
            }
        } else if (entity instanceof HasMetadata) {
            log.status("Applying " + entity.getClass().getSimpleName() + ":" + KubernetesHelper.getName((HasMetadata) entity));
            controller.apply(entity, session.getId());
        } else if (entity != null) {
            log.status("Applying " + entity.getClass().getSimpleName() + ".");
            controller.apply(entity, session.getId());
        }
    }
    entities.addAll(extraEntities);
    // Wait until conditions are meet.
    if (!conditions.isEmpty()) {
        Callable<Boolean> compositeCondition = new CompositeCondition(conditions.values());
        WaitStrategy waitStrategy = new WaitStrategy(compositeCondition, configuration.getWaitTimeout(), configuration.getWaitPollInterval());
        if (!waitStrategy.await()) {
            log.error("Timed out waiting for pods/services!");
            return false;
        } else {
            log.status("All pods/services are currently 'running'!");
        }
    } else {
        log.warn("No pods/services/replication controllers defined in the configuration!");
    }
    return true;
}
Also used : SessionPodsAreReady(io.fabric8.arquillian.kubernetes.await.SessionPodsAreReady) OAuthClient(io.fabric8.openshift.api.model.OAuthClient) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString) Logger(io.fabric8.arquillian.kubernetes.log.Logger) Callable(java.util.concurrent.Callable) HasMetadataComparator(io.fabric8.kubernetes.internal.HasMetadataComparator) ReplicaSet(io.fabric8.kubernetes.api.model.extensions.ReplicaSet) Route(io.fabric8.openshift.api.model.Route) SessionServicesAreReady(io.fabric8.arquillian.kubernetes.await.SessionServicesAreReady) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) WaitStrategy(io.fabric8.arquillian.kubernetes.await.WaitStrategy) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) CompositeCondition(io.fabric8.arquillian.kubernetes.await.CompositeCondition)

Example 40 with Deployment

use of io.fabric8.kubernetes.api.model.apps.Deployment in project fabric8 by jboss-fuse.

the class KubernetesAssert method deployment.

/**
 * Asserts that there is a deployment of the given name
 *
 * @return the assertion object for the deployment
 */
public HasPodSelectionAssert deployment(String deploymentName) {
    String namespace = namespace();
    String qualifiedName = namespace + "." + deploymentName;
    OpenShiftClient openShiftClient = new Controller(client).getOpenShiftClientOrNull();
    if (openShiftClient != null && openShiftClient.supportsOpenShiftAPIGroup(OpenShiftAPIGroups.APPS)) {
        DeploymentConfig deployment = openShiftClient.deploymentConfigs().inNamespace(namespace).withName(deploymentName).get();
        assertThat(deployment).describedAs("DeploymentConfig: " + qualifiedName).isNotNull().metadata().name().isEqualTo(deploymentName);
        return new DeploymentConfigPodsAssert(client, deployment);
    } else {
        Deployment deployment = client.extensions().deployments().inNamespace(namespace).withName(deploymentName).get();
        assertThat(deployment).describedAs("Deployment: " + qualifiedName).isNotNull().metadata().name().isEqualTo(deploymentName);
        return new DeploymentPodsAssert(client, deployment);
    }
}
Also used : OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) Controller(io.fabric8.kubernetes.api.Controller) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig)

Aggregations

File (java.io.File)62 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)52 Test (org.testng.annotations.Test)50 Deployment (io.fabric8.kubernetes.api.model.apps.Deployment)47 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)43 Container (io.fabric8.kubernetes.api.model.Container)32 Service (io.fabric8.kubernetes.api.model.Service)28 Test (org.junit.Test)28 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)27 InputStream (java.io.InputStream)26 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)25 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)25 Deployment (org.jboss.arquillian.container.test.api.Deployment)21 OSGiManifestBuilder (org.jboss.osgi.metadata.OSGiManifestBuilder)21 Asset (org.jboss.shrinkwrap.api.asset.Asset)21 JavaArchive (org.jboss.shrinkwrap.api.spec.JavaArchive)21 IOException (java.io.IOException)20 ServiceTracker (org.osgi.util.tracker.ServiceTracker)20 FileInputStream (java.io.FileInputStream)19 CommandSupport (io.fabric8.itests.support.CommandSupport)18