Search in sources :

Example 86 with Namespace

use of io.fabric8.kubernetes.api.model.Namespace in project fabric8 by fabric8io.

the class SessionListener method loadDependency.

public void loadDependency(Logger log, List<KubernetesList> kubeConfigs, String dependency, Controller controller, Configuration configuration, String namespace) throws Exception {
    // lets test if the dependency is a local string
    String baseDir = System.getProperty("basedir", ".");
    String path = baseDir + "/" + dependency;
    File file = new File(path);
    if (file.exists()) {
        loadDependency(log, kubeConfigs, file, controller, configuration, log, namespace);
    } else {
        String text = readAsString(createURL(dependency));
        Object resources;
        if (text.trim().startsWith("---") || dependency.endsWith(".yml") || dependency.endsWith(".yaml")) {
            resources = loadYaml(text);
        } else {
            resources = loadJson(text);
        }
        addConfig(kubeConfigs, resources, controller, configuration, log, namespace, dependency);
    }
}
Also used : Util.readAsString(io.fabric8.arquillian.utils.Util.readAsString) File(java.io.File)

Example 87 with Namespace

use of io.fabric8.kubernetes.api.model.Namespace in project fabric8 by fabric8io.

the class Configuration method fromMap.

public static Configuration fromMap(Map<String, String> map, KubernetesClient testKubernetesClient) {
    Configuration configuration = new Configuration();
    try {
        configuration.masterUrl = getStringProperty(KUBERNETES_MASTER, map, FALLBACK_CONFIG.getMasterUrl());
        configuration.environment = getStringProperty(FABRIC8_ENVIRONMENT, map, null);
        configuration.environmentInitEnabled = getBooleanProperty(ENVIRONMENT_INIT_ENABLED, map, true);
        configuration.environmentConfigUrl = getKubernetesConfigurationUrl(map);
        configuration.environmentDependencies = Strings.splitAndTrimAsList(getStringProperty(ENVIRONMENT_DEPENDENCIES, map, ""), "\\s+");
        configuration.namespaceLazyCreateEnabled = getBooleanProperty(NAMESPACE_LAZY_CREATE_ENABLED, map, DEFAULT_NAMESPACE_LAZY_CREATE_ENABLED);
        configuration.properties = map;
        String existingNamespace = getStringProperty(NAMESPACE_TO_USE, map, null);
        configuration.sessionId = UUID.randomUUID().toString();
        configuration.namespaceCleanupConfirmationEnabled = getBooleanProperty(NAMESPACE_CLEANUP_CONFIRM_ENABLED, map, false);
        configuration.deleteAllResourcesOnExit = getBooleanProperty(NAMESPACE_DELETE_ALL_RESOURCES_ON_EXIT, map, false);
        configuration.namespaceCleanupTimeout = getLongProperty(NAMESPACE_CLEANUP_TIMEOUT, map, DEFAULT_NAMESPACE_CLEANUP_TIMEOUT);
        configuration.waitTimeout = getLongProperty(WAIT_TIMEOUT, map, DEFAULT_WAIT_TIMEOUT);
        configuration.waitPollInterval = getLongProperty(WAIT_POLL_INTERVAL, map, DEFAULT_WAIT_POLL_INTERVAL);
        configuration.waitForServiceList = Strings.splitAndTrimAsList(getStringProperty(WAIT_FOR_SERVICE_LIST, map, ""), "\\s+");
        configuration.waitForServiceConnectionEnabled = getBooleanProperty(WAIT_FOR_SERVICE_CONNECTION_ENABLED, map, DEFAULT_WAIT_FOR_SERVICE_CONNECTION_ENABLED);
        configuration.waitForServiceConnectionTimeout = getLongProperty(WAIT_FOR_SERVICE_CONNECTION_TIMEOUT, map, DEFAULT_NAMESPACE_CLEANUP_TIMEOUT);
        configuration.ansiLoggerEnabled = getBooleanProperty(ANSI_LOGGER_ENABLED, map, true);
        configuration.kubernetesDomain = getStringProperty(KUBERNETES_DOMAIN, map, "");
        configuration.gofabric8Enabled = getBooleanProperty(GOFABRIC8_ENABLED, map, false);
        configuration.createNamespaceForTest = getBooleanProperty(CREATE_NAMESPACE_FOR_TEST, map, false);
        KubernetesClient kubernetesClient = getOrCreateKubernetesClient(configuration, testKubernetesClient);
        boolean failOnMissingEnvironmentNamespace = getBooleanProperty(FAIL_ON_MISSING_ENVIRONMENT_NAMESPACE, map, false);
        String defaultDevelopNamespace = existingNamespace;
        if (Strings.isNullOrBlank(defaultDevelopNamespace)) {
            defaultDevelopNamespace = kubernetesClient.getNamespace();
        }
        String developNamespace = getStringProperty(DEVELOPMENT_NAMESPACE, map, defaultDevelopNamespace);
        configuration.kubernetesClient = kubernetesClient;
        String environmentNamespace = findNamespaceForEnvironment(configuration.environment, map, kubernetesClient, developNamespace, failOnMissingEnvironmentNamespace);
        String providedNamespace = selectNamespace(environmentNamespace, existingNamespace);
        if (configuration.createNamespaceForTest) {
            configuration.namespace = NAMESPACE_PREFIX + configuration.sessionId;
        } else {
            String namespace = Strings.isNotBlank(providedNamespace) ? providedNamespace : developNamespace;
            ;
            if (Strings.isNullOrBlank(namespace)) {
                namespace = kubernetesClient.getNamespace();
                if (Strings.isNullOrBlank(namespace)) {
                    namespace = KubernetesHelper.defaultNamespace();
                }
            }
            configuration.namespace = namespace;
        }
        // We default to "cleanup=true" when generating namespace and "cleanup=false" when using existing namespace.
        configuration.namespaceCleanupEnabled = getBooleanProperty(NAMESPACE_CLEANUP_ENABLED, map, Strings.isNullOrBlank(providedNamespace));
    } catch (Throwable t) {
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else {
            throw new RuntimeException(t);
        }
    }
    return configuration;
}
Also used : KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient)

Example 88 with Namespace

use of io.fabric8.kubernetes.api.model.Namespace in project fabric8 by fabric8io.

the class Configuration method findNamespaceForEnvironment.

/**
 * Resolves a logical environment name for a project, such as <code>Testing</code> to the physical projcect/team specific
 * namespace value.
 *
 * It tries to find a fabric8.yml file in this folder or a parent folder and loads it and tries to use it to find the
 * namespace for the given environment or uses environment variables to resolve the environment name -> physical namespace
 * @return the namespace
 */
private static String findNamespaceForEnvironment(String environment, Map<String, String> map, KubernetesClient kubernetesClient, String developNamespace, boolean failOnMissingEnvironmentNamespace) {
    String namespace = null;
    if (!Strings.isNullOrBlank(environment)) {
        namespace = Environments.namespaceForEnvironment(kubernetesClient, environment, developNamespace);
        if (Strings.isNotBlank(namespace)) {
            return namespace;
        }
        String basedir = System.getProperty("basedir", ".");
        File folder = new File(basedir);
        ProjectConfig projectConfig = ProjectConfigs.findFromFolder(folder);
        if (projectConfig != null) {
            LinkedHashMap<String, String> environments = projectConfig.getEnvironments();
            if (environments != null) {
                namespace = environments.get(environment);
            }
        }
        String key = environment.toLowerCase() + ".namespace";
        if (Strings.isNullOrBlank(namespace)) {
            // lets try find an environment variable or system property
            namespace = getStringProperty(key, map, null);
        }
        if (Strings.isNullOrBlank(namespace)) {
            if (failOnMissingEnvironmentNamespace) {
                throw new IllegalStateException("A fabric8 environment '" + environment + "' has been specified, but no matching namespace was found in the fabric8.yml file or '" + key + "' system property");
            } else {
                return developNamespace;
            }
        }
    }
    return namespace;
}
Also used : ProjectConfig(io.fabric8.devops.ProjectConfig) File(java.io.File)

Example 89 with Namespace

use of io.fabric8.kubernetes.api.model.Namespace in project fabric8 by fabric8io.

the class ConfigMaps method createConfigMapAnnotations.

private static Map<String, String> createConfigMapAnnotations(Session session, String status) {
    Map<String, String> annotations = new HashMap<>();
    File dir = Util.getProjectBaseDir(session);
    String gitUrl = Util.findGitUrl(session, dir);
    annotations.put(Annotations.Tests.SESSION_ID, session.getId());
    annotations.put(Annotations.Tests.TEST_SESSION_STATUS, status);
    if (Strings.isNotBlank(gitUrl)) {
        annotations.put(Annotations.Builds.GIT_URL, gitUrl);
    }
    // lets see if there's a maven generated set of pom properties
    File pomProperties = new File(dir, "target/maven-archiver/pom.properties");
    if (pomProperties.isFile()) {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream(pomProperties));
            Map<String, String> map = PropertiesHelper.toMap(properties);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (Strings.isNotBlank(key) && Strings.isNotBlank(value)) {
                    annotations.put(Annotations.Project.PREFIX + key, value);
                }
            }
        } catch (IOException e) {
            session.getLogger().warn("Failed to load " + pomProperties + " file to annotate the namespace: " + e);
        }
    }
    return annotations;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) Properties(java.util.Properties) File(java.io.File) HashMap(java.util.HashMap) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Map(java.util.Map) FileInputStream(java.io.FileInputStream)

Example 90 with Namespace

use of io.fabric8.kubernetes.api.model.Namespace in project fabric8 by fabric8io.

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)

Aggregations

IOException (java.io.IOException)81 Test (org.junit.Test)78 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)74 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)65 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)60 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)59 HashMap (java.util.HashMap)59 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)58 FileNotFoundException (java.io.FileNotFoundException)49 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)48 OpenShiftNotAvailableException (io.fabric8.openshift.client.OpenShiftNotAvailableException)48 JSONObject (org.json.JSONObject)44 Service (io.fabric8.kubernetes.api.model.Service)38 Pod (io.fabric8.kubernetes.api.model.Pod)36 ArrayList (java.util.ArrayList)32 File (java.io.File)25 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)24 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)24 Map (java.util.Map)22 ConfigMapBuilder (io.fabric8.kubernetes.api.model.ConfigMapBuilder)21