Search in sources :

Example 1 with AttributeSet

use of io.fabric8.mockwebserver.crud.AttributeSet in project kubernetes-client by fabric8io.

the class KubernetesAttributesExtractor method fromPath.

@Override
public AttributeSet fromPath(String s) {
    if (s == null || s.isEmpty()) {
        return new AttributeSet();
    }
    // Get paths
    HttpUrl url = parseUrlFromPathAndQuery(s);
    Matcher m = PATTERN.matcher(url.encodedPath());
    if (m.matches()) {
        AttributeSet set = new AttributeSet(extract(m).entrySet().stream().map(e -> new Attribute(e.getKey(), e.getValue())).collect(Collectors.toList()));
        set = AttributeSet.merge(set, extractQueryParameters(url));
        LOGGER.debug("fromPath {} : {}", s, set);
        return set;
    }
    return new AttributeSet();
}
Also used : AttributeSet(io.fabric8.mockwebserver.crud.AttributeSet) Matcher(java.util.regex.Matcher) Attribute(io.fabric8.mockwebserver.crud.Attribute) HttpUrl(okhttp3.HttpUrl)

Example 2 with AttributeSet

use of io.fabric8.mockwebserver.crud.AttributeSet in project kubernetes-client by fabric8io.

the class KubernetesAttributesExtractor method extractFieldSelector.

private static AttributeSet extractFieldSelector(HttpUrl url) {
    AttributeSet attributes = new AttributeSet();
    String fieldSelector = url.queryParameter("fieldSelector");
    if (fieldSelector != null) {
        for (String requirement : fieldSelector.split(",")) {
            Attribute field = parseField(requirement);
            if (field != null) {
                attributes = attributes.add(field);
            } else {
                LOGGER.warn("Ignoring unsupported field requirement: {}", requirement);
            }
        }
    }
    return attributes;
}
Also used : AttributeSet(io.fabric8.mockwebserver.crud.AttributeSet) Attribute(io.fabric8.mockwebserver.crud.Attribute)

Example 3 with AttributeSet

use of io.fabric8.mockwebserver.crud.AttributeSet in project kubernetes-client by fabric8io.

the class KubernetesCrudDispatcher method handleGet.

/**
 * Performs a get for the corresponding object from the in-memory db.
 *
 * @param path The path.
 * @return The {@link MockResponse}
 */
@Override
public MockResponse handleGet(String path) {
    if (detectWatchMode(path)) {
        return handleWatch(path);
    }
    MockResponse response = new MockResponse();
    List<String> items = new ArrayList<>();
    AttributeSet query = attributeExtractor.fromPath(path);
    synchronized (map) {
        map.entrySet().stream().filter(entry -> entry.getKey().matches(query)).forEach(entry -> {
            LOGGER.debug("Entry found for query {} : {}", query, entry);
            items.add(entry.getValue());
        });
    }
    if (query.containsKey(KubernetesAttributesExtractor.NAME)) {
        if (!items.isEmpty()) {
            response.setBody(items.get(0));
            response.setResponseCode(HttpURLConnection.HTTP_OK);
        } else {
            response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        response.setBody(kubernetesResponseComposer.compose(items, String.valueOf(resourceVersion.get())));
        response.setResponseCode(HttpURLConnection.HTTP_OK);
    }
    return response;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) StatusBuilder(io.fabric8.kubernetes.api.model.StatusBuilder) URISyntaxException(java.net.URISyntaxException) ZonedDateTime(java.time.ZonedDateTime) KubernetesAttributesExtractor.toKubernetesResource(io.fabric8.kubernetes.client.server.mock.KubernetesAttributesExtractor.toKubernetesResource) LoggerFactory(org.slf4j.LoggerFactory) StatusCause(io.fabric8.kubernetes.api.model.StatusCause) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) CustomResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext) CrudDispatcher(io.fabric8.mockwebserver.crud.CrudDispatcher) Map(java.util.Map) Status(io.fabric8.kubernetes.api.model.Status) JsonNode(com.fasterxml.jackson.databind.JsonNode) URI(java.net.URI) ZoneOffset(java.time.ZoneOffset) MediaType(okhttp3.MediaType) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) AttributeSet(io.fabric8.mockwebserver.crud.AttributeSet) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Set(java.util.Set) UUID(java.util.UUID) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) StatusCauseBuilder(io.fabric8.kubernetes.api.model.StatusCauseBuilder) List(java.util.List) JsonPatch(io.fabric8.zjsonpatch.JsonPatch) Optional(java.util.Optional) PatchType(io.fabric8.kubernetes.client.dsl.base.PatchType) MockResponse(okhttp3.mockwebserver.MockResponse) JsonDiff(io.fabric8.zjsonpatch.JsonDiff) Function(java.util.function.Function) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Action(io.fabric8.kubernetes.client.Watcher.Action) ArrayList(java.util.ArrayList) Utils(io.fabric8.kubernetes.client.utils.Utils) Serialization(io.fabric8.kubernetes.client.utils.Serialization) StreamSupport(java.util.stream.StreamSupport) Logger(org.slf4j.Logger) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Context(io.fabric8.mockwebserver.Context) KubernetesResourceUtil(io.fabric8.kubernetes.client.utils.KubernetesResourceUtil) Attribute(io.fabric8.mockwebserver.crud.Attribute) SocketPolicy(okhttp3.mockwebserver.SocketPolicy) AtomicLong(java.util.concurrent.atomic.AtomicLong) DateTimeFormatter(java.time.format.DateTimeFormatter) Collections(java.util.Collections) MockResponse(okhttp3.mockwebserver.MockResponse) AttributeSet(io.fabric8.mockwebserver.crud.AttributeSet) ArrayList(java.util.ArrayList)

Example 4 with AttributeSet

use of io.fabric8.mockwebserver.crud.AttributeSet in project kubernetes-client by fabric8io.

the class KubernetesCrudDispatcher method processEvent.

private void processEvent(String path, AttributeSet pathAttributes, AttributeSet oldAttributes, String newState) {
    String existing = map.remove(oldAttributes);
    AttributeSet newAttributes = null;
    if (newState != null) {
        newAttributes = kubernetesAttributesExtractor.fromResource(newState);
        // corner case - we need to get the plural from the path
        if (!newAttributes.containsKey(KubernetesAttributesExtractor.PLURAL)) {
            newAttributes = AttributeSet.merge(pathAttributes, newAttributes);
        }
        map.put(newAttributes, newState);
    }
    if (!Objects.equals(existing, newState)) {
        AttributeSet finalAttributeSet = newAttributes;
        watchEventListeners.forEach(listener -> {
            boolean matchesOld = oldAttributes != null && listener.attributeMatches(oldAttributes);
            boolean matchesNew = finalAttributeSet != null && listener.attributeMatches(finalAttributeSet);
            if (matchesOld && matchesNew) {
                listener.sendWebSocketResponse(newState, Action.MODIFIED);
            } else if (matchesOld) {
                listener.sendWebSocketResponse(existing, Action.DELETED);
            } else if (matchesNew) {
                listener.sendWebSocketResponse(newState, Action.ADDED);
            }
        });
        crdProcessor.process(path, Utils.getNonNullOrElse(newState, existing), newState == null);
    }
}
Also used : AttributeSet(io.fabric8.mockwebserver.crud.AttributeSet)

Example 5 with AttributeSet

use of io.fabric8.mockwebserver.crud.AttributeSet in project kubernetes-client by fabric8io.

the class KubernetesAttributesExtractor method extract.

public AttributeSet extract(HasMetadata hasMetadata) {
    AttributeSet metadataAttributes = new AttributeSet();
    String apiVersion = hasMetadata.getApiVersion();
    String api = null;
    String version = null;
    if (!Utils.isNullOrEmpty(apiVersion)) {
        api = ApiVersionUtil.trimGroup(apiVersion);
        version = ApiVersionUtil.trimVersion(apiVersion);
        if (!api.equals(apiVersion)) {
            metadataAttributes = metadataAttributes.add(new Attribute(API, api));
        } else {
            api = null;
        }
        metadataAttributes = metadataAttributes.add(new Attribute(VERSION, version));
    }
    if (!Utils.isNullOrEmpty(hasMetadata.getMetadata().getName())) {
        metadataAttributes = metadataAttributes.add(new Attribute(NAME, hasMetadata.getMetadata().getName()));
        metadataAttributes = metadataAttributes.add(new Attribute(METADATA_NAME, hasMetadata.getMetadata().getName()));
    }
    if (!Utils.isNullOrEmpty(hasMetadata.getMetadata().getNamespace())) {
        metadataAttributes = metadataAttributes.add(new Attribute(NAMESPACE, hasMetadata.getMetadata().getNamespace()));
        metadataAttributes = metadataAttributes.add(new Attribute(METADATA_NAMESPACE, hasMetadata.getMetadata().getNamespace()));
    }
    if (hasMetadata.getMetadata().getLabels() != null) {
        for (Map.Entry<String, String> label : hasMetadata.getMetadata().getLabels().entrySet()) {
            metadataAttributes = metadataAttributes.add(new Attribute(LABEL_KEY_PREFIX + label.getKey(), label.getValue()));
        }
    }
    if (!(hasMetadata instanceof GenericKubernetesResource)) {
        metadataAttributes = metadataAttributes.add(new Attribute(PLURAL, hasMetadata.getPlural()));
    } else {
        Optional<CustomResourceDefinitionContext> context = findCrd(api, version);
        if (context.isPresent()) {
            metadataAttributes = metadataAttributes.add(new Attribute(PLURAL, context.get().getPlural()));
        }
    // else we shouldn't infer the plural without a crd registered - it will come from the path instead
    }
    return metadataAttributes;
}
Also used : CustomResourceDefinitionContext(io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext) AttributeSet(io.fabric8.mockwebserver.crud.AttributeSet) Attribute(io.fabric8.mockwebserver.crud.Attribute) HashMap(java.util.HashMap) Map(java.util.Map) GenericKubernetesResource(io.fabric8.kubernetes.api.model.GenericKubernetesResource)

Aggregations

AttributeSet (io.fabric8.mockwebserver.crud.AttributeSet)35 Attribute (io.fabric8.mockwebserver.crud.Attribute)32 Test (org.junit.jupiter.api.Test)25 CustomResourceDefinitionContext (io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext)6 PodBuilder (io.fabric8.kubernetes.api.model.PodBuilder)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 IngressBuilder (io.fabric8.kubernetes.api.model.extensions.IngressBuilder)4 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)3 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 ObjectMetaBuilder (io.fabric8.kubernetes.api.model.ObjectMetaBuilder)3 DeploymentBuilder (io.fabric8.kubernetes.api.model.apps.DeploymentBuilder)3 PatchType (io.fabric8.kubernetes.client.dsl.base.PatchType)3 MockResponse (okhttp3.mockwebserver.MockResponse)3 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)2 Pod (io.fabric8.kubernetes.api.model.Pod)2 Status (io.fabric8.kubernetes.api.model.Status)2 StatusBuilder (io.fabric8.kubernetes.api.model.StatusBuilder)2 StatusCause (io.fabric8.kubernetes.api.model.StatusCause)2 StatusCauseBuilder (io.fabric8.kubernetes.api.model.StatusCauseBuilder)2