Skip to content
This repository has been archived by the owner on Mar 31, 2022. It is now read-only.

Commit

Permalink
feat(gateway): Add Virtual-Host support
Browse files Browse the repository at this point in the history
  • Loading branch information
brasseld authored and aelamrani committed Aug 29, 2019
1 parent f52485b commit b7bd065
Show file tree
Hide file tree
Showing 21 changed files with 688 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ public ApiModule() {
addDeserializer(PKCS12TrustStore.class, new PKCS12TrustStoreDeserializer(PKCS12TrustStore.class));
addDeserializer(ResponseTemplates.class, new ResponseTemplatesDeserializer(ResponseTemplates.class));
addDeserializer(ResponseTemplate.class, new ResponseTemplateDeserializer(ResponseTemplate.class));
addDeserializer(VirtualHost.class, new VirtualHostDeserializer(VirtualHost.class));

// then serializers:
addSerializer(Api.class, new ApiSerializer(Api.class));
Expand Down Expand Up @@ -96,5 +97,6 @@ public ApiModule() {
addSerializer(PKCS12TrustStore.class, new PKCS12TrustStoreSerializer(PKCS12TrustStore.class));
addSerializer(ResponseTemplates.class, new ResponseTemplatesSerializer(ResponseTemplates.class));
addSerializer(ResponseTemplate.class, new ResponseTemplateSerializer(ResponseTemplate.class));
addSerializer(VirtualHost.class, new VirtualHostSerializer(VirtualHost.class));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@
import io.gravitee.definition.model.*;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;

/**
Expand All @@ -45,12 +42,34 @@ public Proxy deserialize(JsonParser jp, DeserializationContext ctxt)
JsonNode node = jp.getCodec().readTree(jp);

Proxy proxy = new Proxy();
final JsonNode contextPath = node.get("context_path");
if (contextPath != null) {
String sContextPath = formatContextPath(contextPath.asText());
proxy.setContextPath(sContextPath);
} else {
throw ctxt.mappingException("[api] API must have a valid context path");

// To ensure backward compatibility
final JsonNode contextPathNode = node.get("context_path");
if (contextPathNode != null) {
String sContextPath = formatContextPath(contextPathNode.asText());
VirtualHost defaultHost = new VirtualHost();
defaultHost.setPath(sContextPath);
proxy.setVirtualHosts(Collections.singletonList(defaultHost));
}

final JsonNode virtualHostsNode = node.get("virtual_hosts");
if (virtualHostsNode != null && virtualHostsNode.isArray()) {
List<VirtualHost> virtualHosts = new ArrayList<>();
virtualHostsNode.elements().forEachRemaining(node1 ->
{
try {
virtualHosts.add(node1.traverse(jp.getCodec()).readValueAs(VirtualHost.class));
} catch (IOException e) {
e.printStackTrace();
}
});

proxy.setVirtualHosts(virtualHosts);
}

// Check that there is, at least, a virtual host
if (proxy.getVirtualHosts() == null || proxy.getVirtualHosts().isEmpty()) {
ctxt.reportBadDefinition(Proxy.class, "[api] API must define at least a single context_path or one or multiple virtual_hosts");
}

final JsonNode nodeEndpoints = node.get("endpoints");
Expand All @@ -73,7 +92,7 @@ public Proxy deserialize(JsonParser jp, DeserializationContext ctxt)
if (group.getEndpoints() != null) {
for (Endpoint endpoint : group.getEndpoints()) {
if (endpointNames.contains(endpoint.getName())) {
throw ctxt.mappingException("[api] API endpoint names and group names must be unique");
ctxt.reportBadDefinition(Proxy.class, "[api] API endpoint names and group names must be unique");
}
endpointNames.add(endpoint.getName());
}
Expand All @@ -87,6 +106,11 @@ public Proxy deserialize(JsonParser jp, DeserializationContext ctxt)
proxy.setStripContextPath(stripContextNode.asBoolean(false));
}

JsonNode preserveHostNode = node.get("preserve_host");
if (preserveHostNode != null) {
proxy.setPreserveHost(preserveHostNode.asBoolean(false));
}

JsonNode failoverNode = node.get("failover");
if (failoverNode != null) {
Failover failover = failoverNode.traverse(jp.getCodec()).readValueAs(Failover.class);
Expand Down Expand Up @@ -131,7 +155,7 @@ private void createEndpointGroups(JsonNode node, ObjectCodec codec, Proxy proxy,
EndpointGroup group = jsonNode.traverse(codec).readValueAs(EndpointGroup.class);
boolean added = groups.add(group);
if (!added) {
throw ctxt.mappingException("[api] API must have single endpoint group names");
ctxt.reportBadDefinition(Proxy.class, "[api] API must have single endpoint group names");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.definition.jackson.datatype.api.deser;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import io.gravitee.definition.model.VirtualHost;

import java.io.IOException;

/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public class VirtualHostDeserializer extends StdScalarDeserializer<VirtualHost> {

public VirtualHostDeserializer(Class<VirtualHost> vc) {
super(vc);
}

@Override
public VirtualHost deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
JsonNode node = jp.getCodec().readTree(jp);

VirtualHost vhost = new VirtualHost();

JsonNode hostNode = node.get("host");
if (hostNode != null) {
vhost.setHost(hostNode.asText());
}

JsonNode pathNode = node.get("path");
if (pathNode != null) {
vhost.setPath(formatContextPath(pathNode.asText()));
} else {
vhost.setPath("/");
}

vhost.setOverrideEntrypoint(node.path("override_entrypoint").asBoolean(false));

return vhost;
}

private String formatContextPath(String contextPath) {
String [] parts = contextPath.split("/");
StringBuilder finalPath = new StringBuilder("/");

for(String part : parts) {
if (! part.isEmpty()) {
finalPath.append(part).append('/');
}
}

return finalPath.deleteCharAt(finalPath.length() - 1).toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,23 @@ public ProxySerializer(Class<Proxy> t) {
@Override
public void serialize(Proxy proxy, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField("context_path", proxy.getContextPath());

if (proxy.getVirtualHosts() != null) {
jgen.writeArrayFieldStart("virtual_hosts");
proxy.getVirtualHosts().forEach(vhost -> {
try {
jgen.writeObject(vhost);
} catch (IOException e) {
e.printStackTrace();
}
});
jgen.writeEndArray();
}

jgen.writeBooleanField("strip_context_path", proxy.isStripContextPath());

jgen.writeBooleanField("preserve_host", proxy.isPreserveHost());

if (proxy.getLogging() != null) {
jgen.writeObjectField("logging", proxy.getLogging());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.definition.jackson.datatype.api.ser;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer;
import io.gravitee.definition.model.VirtualHost;

import java.io.IOException;

/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public class VirtualHostSerializer extends StdScalarSerializer<VirtualHost> {

public VirtualHostSerializer(Class<VirtualHost> t) {
super(t);
}

@Override
public void serialize(VirtualHost vhost, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();

if (vhost.getHost() != null && ! vhost.getHost().isEmpty()) {
jgen.writeStringField("host", vhost.getHost());
}

if (vhost.getPath() != null && ! vhost.getPath().isEmpty()) {
jgen.writeStringField("path", vhost.getPath());
}

if (vhost.isOverrideEntrypoint()) {
jgen.writeBooleanField("override_entrypoint", vhost.isOverrideEntrypoint());
}

jgen.writeEndObject();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ public class ApiDeserializerTest extends AbstractTest {
public void definition_defaultHttpConfig() throws Exception {
Api api = load("/io/gravitee/definition/jackson/api-defaulthttpconfig.json", Api.class);

Assert.assertTrue(api.getProxy().isPreserveHost());

Endpoint endpoint = api.getProxy().getGroups().iterator().next().getEndpoints().iterator().next();
Assert.assertEquals("http://localhost:1234", endpoint.getTarget());
Assert.assertSame(HttpEndpoint.class, endpoint.getClass());
Expand Down Expand Up @@ -77,13 +79,16 @@ public void definition_noPath() throws Exception {
public void definition_reformatContextPath() throws Exception {
Api api = load("/io/gravitee/definition/jackson/api-reformat-contextpath.json", Api.class);

Assert.assertNotNull(api.getProxy().getContextPath());
Assert.assertEquals("/my-api/team", api.getProxy().getContextPath());
Assert.assertNotNull(api.getProxy().getVirtualHosts());
Assert.assertFalse(api.getProxy().getVirtualHosts().isEmpty());
Assert.assertEquals("/my-api/team", api.getProxy().getVirtualHosts().iterator().next().getPath());
Assert.assertNull(api.getProxy().getVirtualHosts().iterator().next().getHost());
Assert.assertFalse(api.getProxy().getVirtualHosts().iterator().next().isOverrideEntrypoint());
}

@Test(expected = JsonMappingException.class)
public void definition_contextPathExpected() throws Exception {
Api api = load("/io/gravitee/definition/jackson/api-no-contextpath.json", Api.class);
load("/io/gravitee/definition/jackson/api-no-contextpath.json", Api.class);
}

@Test
Expand Down Expand Up @@ -617,4 +622,23 @@ public void definition_withResponseTemplates() throws Exception {
Assert.assertEquals("header1", responseTemplate.getHeaders().get("x-header1"));
Assert.assertEquals("header2", responseTemplate.getHeaders().get("x-header2"));
}

@Test
public void definition_virtualhosts() throws Exception {
Api api = load("/io/gravitee/definition/jackson/api-virtualhosts.json", Api.class);

Assert.assertNotNull(api.getProxy().getVirtualHosts());
Assert.assertEquals(2, api.getProxy().getVirtualHosts().size());

VirtualHost host1 = api.getProxy().getVirtualHosts().get(0);
VirtualHost host2 = api.getProxy().getVirtualHosts().get(1);

Assert.assertEquals("localhost", host1.getHost());
Assert.assertEquals("/my-api", host1.getPath());
Assert.assertTrue(host1.isOverrideEntrypoint());

Assert.assertNull(host2.getHost());
Assert.assertEquals("/my-api2", host2.getPath());
Assert.assertFalse(host2.isOverrideEntrypoint());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -289,4 +289,12 @@ public void definition_withResponseTemplates() throws Exception {
String generatedJsonDefinition = objectMapper().writeValueAsString(api);
Assert.assertNotNull(generatedJsonDefinition);
}

@Test
public void definition_virtualhosts() throws Exception {
Api api = load("/io/gravitee/definition/jackson/api-virtualhosts.json", Api.class);

String generatedJsonDefinition = objectMapper().writeValueAsString(api);
Assert.assertNotNull(generatedJsonDefinition);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,26 @@ public class ServicesSerializerTest extends AbstractTest {
@Test
public void definition_withServices() throws Exception {
String oldDefinition = "/io/gravitee/definition/jackson/services/api-withservices.json";
String definition = "/io/gravitee/definition/jackson/services/api-withservices-v2.json";
String expectedDefinition = "/io/gravitee/definition/jackson/services/api-withservices-v2-expected.json";
Api api = load(oldDefinition, Api.class);

String generatedJsonDefinition = objectMapper().writeValueAsString(api);
Assert.assertNotNull(generatedJsonDefinition);

String expected = IOUtils.toString(read(definition));
String expected = IOUtils.toString(read(expectedDefinition));
JSONAssert.assertEquals(expected, generatedJsonDefinition, false);
}

@Test
public void definition_withServices_v2() throws Exception {
String definition = "/io/gravitee/definition/jackson/services/api-withservices-v2.json";
String expectedDefinition = "/io/gravitee/definition/jackson/services/api-withservices-v2-expected.json";
Api api = load(definition, Api.class);

String generatedJsonDefinition = objectMapper().writeValueAsString(api);
Assert.assertNotNull(generatedJsonDefinition);

String expected = IOUtils.toString(read(definition));
String expected = IOUtils.toString(read(expectedDefinition));
JSONAssert.assertEquals(expected, generatedJsonDefinition, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ public class EndpointDiscoveryServiceSerializerTest extends AbstractTest {
@Test
public void definition_withoutEndpointDiscovery() throws Exception {
String definition = "/io/gravitee/definition/jackson/services/discovery/api-withoutservice.json";
String expectedDefinition = "/io/gravitee/definition/jackson/services/discovery/api-withoutservice-expected.json";
Api api = load(definition, Api.class);

String generatedJsonDefinition = objectMapper().writeValueAsString(api);
Assert.assertNotNull(generatedJsonDefinition);

String expected = IOUtils.toString(read(definition));
String expected = IOUtils.toString(read(expectedDefinition));
JSONAssert.assertEquals(expected, generatedJsonDefinition, false);

EndpointDiscoveryService endpointDiscoveryService = api.getService(EndpointDiscoveryService.class);
Expand All @@ -49,12 +50,14 @@ public void definition_withoutEndpointDiscovery() throws Exception {
@Ignore("Service discovery service has been moved from API to group")
public void definition_withEndpointDiscovery_consul() throws Exception {
String definition = "/io/gravitee/definition/jackson/services/discovery/api-withservice-consul.json";
String expectedDefinition = "/io/gravitee/definition/jackson/services/discovery/api-withservice-consul-expected.json";

Api api = load(definition, Api.class);

String generatedJsonDefinition = objectMapper().writeValueAsString(api);
Assert.assertNotNull(generatedJsonDefinition);

String expected = IOUtils.toString(read(definition));
String expected = IOUtils.toString(read(expectedDefinition));
JSONAssert.assertEquals(expected, generatedJsonDefinition, false);
}
}
Loading

0 comments on commit b7bd065

Please sign in to comment.