Search in sources :

Example 6 with Service

use of org.apache.knox.gateway.topology.Service in project knox by apache.

the class HaProviderDeploymentContributorTest method testProviderLevelParams.

/**
 * Basically, a backward-compatibility test to ensure that HaProvider service params specified ONLY at the provider
 * level still work.
 */
@Test
public void testProviderLevelParams() throws Exception {
    // Define some provider params
    Map<String, String> providerParams = new HashMap<>();
    // Specify all the possible params at the HaProvider level for TestRoleTwo
    providerParams.put("TestRoleOne", "enabled=false;" + "maxRetryAttempts=5;" + "retrySleep=50;" + "maxFailoverAttempts=4;" + "failoverSleep=40;" + "zookeeperNamespace=testRoleOne;" + "zookeeperEnsemble=http://host1:2181,http://host2:2181");
    Provider haProvider = createHaProvider(providerParams);
    // Define the topology content (e.g., services)
    Collection<Service> topologyServices = new HashSet<>();
    // A service with no param overrides
    Service testRoleOneService = EasyMock.createNiceMock(Service.class);
    EasyMock.expect(testRoleOneService.getRole()).andReturn("TestRoleOne").anyTimes();
    EasyMock.expect(testRoleOneService.getName()).andReturn("TestRoleOneService").anyTimes();
    EasyMock.expect(testRoleOneService.getParams()).andReturn(Collections.emptyMap()).anyTimes();
    EasyMock.replay(testRoleOneService);
    topologyServices.add(testRoleOneService);
    Topology topology = EasyMock.createNiceMock(Topology.class);
    EasyMock.expect(topology.getServices()).andReturn(topologyServices).anyTimes();
    EasyMock.replay(topology);
    WebArchive war = EasyMock.createNiceMock(WebArchive.class);
    EasyMock.replay(war);
    DeploymentContext context = new DescriptorCaptureDeploymentContext(topology, war);
    // Invoke the contributor
    HaProviderDeploymentContributor haPDC = new HaProviderDeploymentContributor();
    haPDC.contributeProvider(context, haProvider);
    HaDescriptor descriptor = context.getDescriptor("ha.provider.descriptor");
    assertNotNull(descriptor);
    assertEquals(1, descriptor.getServiceConfigs().size());
    validateServiceHaConfig(descriptor.getServiceConfig("TestRoleOne"), false, 40, 4, 50, 5, "testRoleOne", "http://host1:2181,http://host2:2181");
}
Also used : HashMap(java.util.HashMap) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) Service(org.apache.knox.gateway.topology.Service) Topology(org.apache.knox.gateway.topology.Topology) Provider(org.apache.knox.gateway.topology.Provider) DeploymentContext(org.apache.knox.gateway.deploy.DeploymentContext) HaDescriptor(org.apache.knox.gateway.ha.provider.HaDescriptor) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 7 with Service

use of org.apache.knox.gateway.topology.Service in project knox by apache.

the class HaProviderDeploymentContributorTest method testServiceLevelParamOverrides_NoProviderParams.

/**
 * Simple test verifying that HaProvider service params specified ONLY at the service level works.
 */
@Test
public void testServiceLevelParamOverrides_NoProviderParams() throws Exception {
    // Define some provider params
    Map<String, String> providerParams = new HashMap<>();
    // Specify all the possible params at the HaProvider level for TestRoleTwo
    providerParams.put("TestRoleOne", "");
    Provider haProvider = createHaProvider(providerParams);
    // Define the topology content (e.g., services)
    Collection<Service> topologyServices = new HashSet<>();
    // Specify all the possible params in the TestRoleOne service level
    Map<String, String> testRoleOneParams = new HashMap<>();
    testRoleOneParams.put("enabled", "true");
    testRoleOneParams.put("maxRetryAttempts", "6");
    testRoleOneParams.put("retrySleep", "60");
    testRoleOneParams.put("maxFailoverAttempts", "8");
    testRoleOneParams.put("failoverSleep", "80");
    testRoleOneParams.put("zookeeperNamespace", "testRoleOneOverride");
    testRoleOneParams.put("zookeeperEnsemble", "http://host3:2181,http://host4:2181");
    // A service with all the params overriden
    Service testRoleOneService = EasyMock.createNiceMock(Service.class);
    EasyMock.expect(testRoleOneService.getRole()).andReturn("TestRoleOne").anyTimes();
    EasyMock.expect(testRoleOneService.getName()).andReturn("TestRoleOneService").anyTimes();
    EasyMock.expect(testRoleOneService.getParams()).andReturn(testRoleOneParams).anyTimes();
    EasyMock.replay(testRoleOneService);
    topologyServices.add(testRoleOneService);
    Topology topology = EasyMock.createNiceMock(Topology.class);
    EasyMock.expect(topology.getServices()).andReturn(topologyServices).anyTimes();
    EasyMock.replay(topology);
    WebArchive war = EasyMock.createNiceMock(WebArchive.class);
    EasyMock.replay(war);
    DeploymentContext context = new DescriptorCaptureDeploymentContext(topology, war);
    // Invoke the contributor
    HaProviderDeploymentContributor haPDC = new HaProviderDeploymentContributor();
    haPDC.contributeProvider(context, haProvider);
    HaDescriptor descriptor = context.getDescriptor("ha.provider.descriptor");
    assertNotNull(descriptor);
    assertEquals(1, descriptor.getServiceConfigs().size());
    validateServiceHaConfig(descriptor.getServiceConfig("TestRoleOne"), true, 80, 8, 60, 6, "testRoleOneOverride", "http://host3:2181,http://host4:2181");
}
Also used : HashMap(java.util.HashMap) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) Service(org.apache.knox.gateway.topology.Service) Topology(org.apache.knox.gateway.topology.Topology) Provider(org.apache.knox.gateway.topology.Provider) DeploymentContext(org.apache.knox.gateway.deploy.DeploymentContext) HaDescriptor(org.apache.knox.gateway.ha.provider.HaDescriptor) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 8 with Service

use of org.apache.knox.gateway.topology.Service in project knox by apache.

the class JerseyDeploymentContributorTest method testDeploymentContributors.

@Test
public void testDeploymentContributors() throws Exception {
    JerseyDispatchDeploymentContributor providerContributor = new JerseyDispatchDeploymentContributor();
    assertThat(providerContributor.getRole(), is("pivot"));
    assertThat(providerContributor.getName(), is("jersey"));
    MockJerseyService serviceContributor = new MockJerseyService();
    WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "test-archive");
    Topology topology = new Topology();
    topology.setName("test-topology");
    Provider provider = new Provider();
    provider.setRole("pivot");
    provider.setName("jersey");
    provider.setEnabled(true);
    topology.addProvider(provider);
    GatewayDescriptor descriptor = GatewayDescriptorFactory.create();
    DeploymentContext context = EasyMock.createNiceMock(DeploymentContext.class);
    EasyMock.expect(context.getWebArchive()).andReturn(webArchive).anyTimes();
    EasyMock.expect(context.getTopology()).andReturn(topology).anyTimes();
    EasyMock.expect(context.getGatewayDescriptor()).andReturn(descriptor).anyTimes();
    context.contributeFilter(EasyMock.<Service>isA(Service.class), EasyMock.<ResourceDescriptor>isA(ResourceDescriptor.class), EasyMock.<String>isA(String.class), EasyMock.<String>isA(String.class), EasyMock.<List>isA(List.class));
    EasyMock.expectLastCall().andDelegateTo(new MockDeploymentContext(context, providerContributor, provider)).anyTimes();
    EasyMock.replay(context);
    // Just make sure they don't blow up.
    providerContributor.initializeContribution(context);
    serviceContributor.initializeContribution(context);
    Service service = new Service();
    service.setRole("test-service-role");
    service.setName("test-service-name");
    service.addUrl("http://test-service-host:777/test-service-path");
    // This should end up calling providerContributor.contributeFilter
    serviceContributor.contributeService(context, service);
    ResourceDescriptor resource = context.getGatewayDescriptor().resources().get(0);
    // Just make sure they don't blow up.
    serviceContributor.finalizeContribution(context);
    providerContributor.finalizeContribution(context);
    /*
    GatewayDescriptorFactory.store( descriptor, "xml", new PrintWriter( System.out ) );
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <gateway>
      <resource>
        <role>test-service-role</role>
        <pattern>test-service/?**</pattern>
        <filter>
          <role>dispatch</role>
          <name>jersey</name>
          <class>org.glassfish.jersey.servlet.ServletContainer</class>
          <param>
            <name>jersey.config.server.provider.packages</name>
            <value>test-package-1;test-package-2</value>
          </param>
        </filter>
      </resource>
      <resource>
        <role>test-service-role</role>
        <pattern>test-service/**?**</pattern>
        <filter>
          <role>dispatch</role>
          <name>jersey</name>
          <class>org.glassfish.jersey.servlet.ServletContainer</class>
          <param>
            <name>jersey.config.server.provider.packages</name>
            <value>test-package-1;test-package-2</value>
          </param>
        </filter>
      </resource>
    </gateway>
    */
    List<ResourceDescriptor> resources = context.getGatewayDescriptor().resources();
    assertThat(resources.size(), is(2));
    resource = resources.get(0);
    assertThat(resource.role(), is("test-service-role"));
    assertThat(resource.pattern(), is("test-service/?**"));
    List<FilterDescriptor> filters = resource.filters();
    assertThat(filters.size(), is(1));
    FilterDescriptor filter = filters.get(0);
    assertThat(filter.role(), is("pivot"));
    assertThat(filter.name(), is("jersey"));
    assertThat(filter.impl(), is("org.glassfish.jersey.servlet.ServletContainer"));
    List<FilterParamDescriptor> params = filter.params();
    assertThat(params.size(), is(1));
    FilterParamDescriptor param = params.get(0);
    assertThat(param.name(), is("jersey.config.server.provider.packages"));
    assertThat(param.value(), is("test-package-1;test-package-2"));
    resource = resources.get(1);
    assertThat(resource.role(), is("test-service-role"));
    assertThat(resource.pattern(), is("test-service/**?**"));
    filters = resource.filters();
    assertThat(filters.size(), is(1));
    filter = filters.get(0);
    assertThat(filter.role(), is("pivot"));
    assertThat(filter.name(), is("jersey"));
    assertThat(filter.impl(), is("org.glassfish.jersey.servlet.ServletContainer"));
    params = filter.params();
    assertThat(params.size(), is(1));
    param = params.get(0);
    assertThat(param.name(), is("jersey.config.server.provider.packages"));
    assertThat(param.value(), is("test-package-1;test-package-2"));
}
Also used : GatewayDescriptor(org.apache.knox.gateway.descriptor.GatewayDescriptor) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) FilterParamDescriptor(org.apache.knox.gateway.descriptor.FilterParamDescriptor) Service(org.apache.knox.gateway.topology.Service) Topology(org.apache.knox.gateway.topology.Topology) Provider(org.apache.knox.gateway.topology.Provider) DeploymentContext(org.apache.knox.gateway.deploy.DeploymentContext) FilterDescriptor(org.apache.knox.gateway.descriptor.FilterDescriptor) List(java.util.List) ResourceDescriptor(org.apache.knox.gateway.descriptor.ResourceDescriptor) Test(org.junit.Test)

Example 9 with Service

use of org.apache.knox.gateway.topology.Service in project knox by apache.

the class HaProviderDeploymentContributor method contributeProvider.

@Override
public void contributeProvider(DeploymentContext context, Provider provider) {
    Topology topology = context.getTopology();
    Map<String, String> params = provider.getParams();
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    for (Entry<String, String> entry : params.entrySet()) {
        String role = entry.getKey();
        String roleParams = entry.getValue();
        // Create the config based on whatever is specified at the provider level
        HaServiceConfig config = HaDescriptorFactory.createServiceConfig(role, roleParams);
        // Check for service-level param overrides
        Map<String, String> serviceLevelParams = null;
        for (Service s : topology.getServices()) {
            if (s.getRole().equals(role)) {
                serviceLevelParams = s.getParams();
                break;
            }
        }
        // Apply any service-level param overrides
        applyParamOverrides(config, serviceLevelParams);
        // Add the reconciled HA service config to the descriptor
        descriptor.addServiceConfig(config);
    }
    StringWriter writer = new StringWriter();
    try {
        HaDescriptorManager.store(descriptor, writer);
    } catch (IOException e) {
        LOG.failedToWriteHaDescriptor(e);
    }
    String asset = writer.toString();
    context.getWebArchive().addAsWebInfResource(new StringAsset(asset), HaServletContextListener.DESCRIPTOR_DEFAULT_FILE_NAME);
    context.addDescriptor(HA_DESCRIPTOR_NAME, descriptor);
}
Also used : StringAsset(org.jboss.shrinkwrap.api.asset.StringAsset) StringWriter(java.io.StringWriter) Service(org.apache.knox.gateway.topology.Service) Topology(org.apache.knox.gateway.topology.Topology) IOException(java.io.IOException) HaDescriptor(org.apache.knox.gateway.ha.provider.HaDescriptor) HaServiceConfig(org.apache.knox.gateway.ha.provider.HaServiceConfig)

Example 10 with Service

use of org.apache.knox.gateway.topology.Service in project knox by apache.

the class ServiceTestResource method serviceTest.

@GET
@Produces({ APPLICATION_XML, APPLICATION_JSON })
public ServiceTestWrapper serviceTest(@QueryParam("username") String username, @QueryParam("password") String password) {
    List<ServiceTest> tests = new ArrayList<>();
    List<String> messages = new ArrayList<>();
    String authString;
    GatewayConfig config = (GatewayConfig) request.getServletContext().getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    SSLContext ctx = null;
    CloseableHttpClient client;
    String id = getTopologyName();
    Topology topology = getTopology(id);
    // Create Authorization String
    if (username != null && password != null) {
        authString = "Basic " + Base64.encodeAsString((username + ":" + password).getBytes());
    } else if (request.getHeader("Authorization") != null) {
        authString = request.getHeader("Authorization");
    } else {
        authString = null;
    }
    // Attempt to build SSL context for HTTP client.
    try {
        ctx = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        messages.add(e.getMessage());
    }
    // Initialize the HTTP client
    if (ctx == null) {
        client = HttpClients.createDefault();
    } else {
        client = HttpClients.custom().setSslcontext(ctx).build();
    }
    if (topology != null) {
        for (Service s : topology.getServices()) {
            List<String> urls = getServiceTestURLs(config, s.getRole(), topology);
            // Make sure we handle a case where no URLs are found.
            if (urls.size() <= 0) {
                ServiceTest test = new ServiceTest(s);
                test.setMessage("This service did not contain any test URLs");
            }
            for (String url : urls) {
                HttpGet req = new HttpGet();
                ServiceTest test = new ServiceTest(s, url);
                if (authString != null) {
                    req.setHeader("Authorization", authString);
                } else {
                    messages.add("No credentials provided. Expect HTTP 401 responses.");
                }
                try {
                    req.setURI(new URIBuilder(url).build());
                    CloseableHttpResponse res = client.execute(req);
                    String contentLength = "Content-Length:" + res.getEntity().getContentLength();
                    String contentType = (res.getEntity().getContentType() != null) ? res.getEntity().getContentType().toString() : "No-contenttype";
                    test.setResponseContent(contentLength + "," + contentType);
                    test.setHttpCode(res.getStatusLine().getStatusCode());
                    res.close();
                } catch (IOException e) {
                    messages.add("Exception: " + e.getMessage());
                    test.setMessage(e.getMessage());
                } catch (URISyntaxException e) {
                    test.setMessage(e.getMessage());
                } catch (Exception e) {
                    messages.add(e.getMessage());
                    test.setMessage(e.getMessage());
                } finally {
                    req.releaseConnection();
                    tests.add(test);
                }
            }
        }
    } else {
        messages.add("Topology " + id + " not found");
    }
    try {
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ServiceTestWrapper stw = new ServiceTestWrapper();
    stw.setTests(tests);
    stw.setMessages(messages);
    return stw;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) Service(org.apache.knox.gateway.topology.Service) TopologyService(org.apache.knox.gateway.services.topology.TopologyService) SSLContext(javax.net.ssl.SSLContext) Topology(org.apache.knox.gateway.topology.Topology) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

Service (org.apache.knox.gateway.topology.Service)25 Topology (org.apache.knox.gateway.topology.Topology)22 Test (org.junit.Test)18 Provider (org.apache.knox.gateway.topology.Provider)17 HashMap (java.util.HashMap)13 File (java.io.File)11 GatewayConfig (org.apache.knox.gateway.config.GatewayConfig)9 GatewayTestConfig (org.apache.knox.gateway.GatewayTestConfig)7 DefaultGatewayServices (org.apache.knox.gateway.services.DefaultGatewayServices)7 ServiceLifecycleException (org.apache.knox.gateway.services.ServiceLifecycleException)7 Param (org.apache.knox.gateway.topology.Param)7 DeploymentContext (org.apache.knox.gateway.deploy.DeploymentContext)6 WebArchive (org.jboss.shrinkwrap.api.spec.WebArchive)6 URL (java.net.URL)5 HaDescriptor (org.apache.knox.gateway.ha.provider.HaDescriptor)5 EnterpriseArchive (org.jboss.shrinkwrap.api.spec.EnterpriseArchive)5 Document (org.w3c.dom.Document)5 HashSet (java.util.HashSet)4 Digester (org.apache.commons.digester3.Digester)4 TopologyBuilder (org.apache.knox.gateway.topology.builder.TopologyBuilder)4