Search in sources :

Example 1 with ServiceDefinition

use of org.apache.knox.gateway.service.definition.ServiceDefinition in project knox by apache.

the class ServiceDefinitionDeploymentContributorTest method testServiceAttributeUseTwoWaySSLParamOverride.

/**
 * Test that service param useTwoWaySsl in topologies overrides the corresponding custom dispatch property.
 */
@Test
public void testServiceAttributeUseTwoWaySSLParamOverride() throws Exception {
    final String TEST_SERVICE_ROLE = "Test";
    final String USE_TWO_WAY_SSL_PARAM = "useTwoWaySsl";
    UrlRewriteRulesDescriptor clusterRules = EasyMock.createNiceMock(UrlRewriteRulesDescriptor.class);
    EasyMock.replay(clusterRules);
    UrlRewriteRulesDescriptor svcRules = EasyMock.createNiceMock(UrlRewriteRulesDescriptor.class);
    EasyMock.replay(svcRules);
    ServiceDefinition svcDef = EasyMock.createNiceMock(ServiceDefinition.class);
    EasyMock.expect(svcDef.getRole()).andReturn(TEST_SERVICE_ROLE).anyTimes();
    List<Route> svcRoutes = new ArrayList<>();
    Route route = EasyMock.createNiceMock(Route.class);
    List<Rewrite> filters = new ArrayList<>();
    EasyMock.expect(route.getRewrites()).andReturn(filters).anyTimes();
    svcRoutes.add(route);
    EasyMock.replay(route);
    EasyMock.expect(svcDef.getRoutes()).andReturn(svcRoutes).anyTimes();
    CustomDispatch cd = EasyMock.createNiceMock(CustomDispatch.class);
    EasyMock.expect(cd.getClassName()).andReturn("TestDispatch").anyTimes();
    EasyMock.expect(cd.getHaClassName()).andReturn("TestHADispatch").anyTimes();
    EasyMock.expect(cd.getHaContributorName()).andReturn(null).anyTimes();
    // Let useTwoWaySsl be FALSE by default
    EasyMock.expect(cd.getUseTwoWaySsl()).andReturn(false).anyTimes();
    EasyMock.replay(cd);
    EasyMock.expect(svcDef.getDispatch()).andReturn(cd).anyTimes();
    EasyMock.replay(svcDef);
    ServiceDefinitionDeploymentContributor sddc = new ServiceDefinitionDeploymentContributor(svcDef, svcRules);
    DeploymentContext context = EasyMock.createNiceMock(DeploymentContext.class);
    EasyMock.expect(context.getDescriptor("rewrite")).andReturn(clusterRules).anyTimes();
    GatewayConfig gc = EasyMock.createNiceMock(GatewayConfig.class);
    EasyMock.expect(gc.isXForwardedEnabled()).andReturn(false).anyTimes();
    EasyMock.expect(gc.isCookieScopingToPathEnabled()).andReturn(false).anyTimes();
    EasyMock.replay(gc);
    EasyMock.expect(context.getGatewayConfig()).andReturn(gc).anyTimes();
    // Configure the HaProvider
    Topology topology = EasyMock.createNiceMock(Topology.class);
    List<Provider> providers = new ArrayList<>();
    Provider haProvider = EasyMock.createNiceMock(Provider.class);
    EasyMock.expect(haProvider.getRole()).andReturn("ha").anyTimes();
    EasyMock.expect(haProvider.isEnabled()).andReturn(true).anyTimes();
    Map<String, String> providerParams = new HashMap<>();
    providerParams.put(TEST_SERVICE_ROLE, "whatever");
    EasyMock.expect(haProvider.getParams()).andReturn(providerParams).anyTimes();
    EasyMock.replay(haProvider);
    providers.add(haProvider);
    EasyMock.expect(topology.getProviders()).andReturn(providers).anyTimes();
    EasyMock.replay(topology);
    EasyMock.expect(context.getTopology()).andReturn(topology).anyTimes();
    TestGatewayDescriptor gd = new TestGatewayDescriptor();
    EasyMock.expect(context.getGatewayDescriptor()).andReturn(gd).anyTimes();
    EasyMock.replay(context);
    // Configure the service with the useTwoWaySsl param to OVERRIDE the value in the service definition
    Service service = EasyMock.createNiceMock(Service.class);
    Map<String, String> svcParams = new HashMap<>();
    svcParams.put(USE_TWO_WAY_SSL_PARAM, "true");
    EasyMock.expect(service.getParams()).andReturn(svcParams).anyTimes();
    EasyMock.replay(service);
    sddc.contributeService(context, service);
    List<ResourceDescriptor> resources = gd.resources();
    assertEquals(1, gd.resources().size());
    ResourceDescriptor res = gd.resources().get(0);
    assertNotNull(res);
    List<FilterDescriptor> filterList = res.filters();
    assertEquals(1, filterList.size());
    FilterDescriptor f = filterList.get(0);
    assertNotNull(f);
    assertEquals("dispatch", f.role());
    List<FilterParamDescriptor> fParams = f.params();
    assertNotNull(fParams);
    // Collect the values of filter params named useTwoWaySsl
    List<String> useTwoWaySslFilterParamValues = new ArrayList<>();
    for (FilterParamDescriptor param : fParams) {
        if (param.name().equals(USE_TWO_WAY_SSL_PARAM)) {
            useTwoWaySslFilterParamValues.add(param.value());
        }
    }
    assertEquals("Expected only a single filter param named " + USE_TWO_WAY_SSL_PARAM, 1, useTwoWaySslFilterParamValues.size());
    assertEquals("Expected the service param to override the service definition value for " + USE_TWO_WAY_SSL_PARAM, "true", useTwoWaySslFilterParamValues.get(0));
}
Also used : CustomDispatch(org.apache.knox.gateway.service.definition.CustomDispatch) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UrlRewriteRulesDescriptor(org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor) FilterDescriptor(org.apache.knox.gateway.descriptor.FilterDescriptor) ServiceDefinition(org.apache.knox.gateway.service.definition.ServiceDefinition) Route(org.apache.knox.gateway.service.definition.Route) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) 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) Rewrite(org.apache.knox.gateway.service.definition.Rewrite) ResourceDescriptor(org.apache.knox.gateway.descriptor.ResourceDescriptor) Test(org.junit.Test)

Example 2 with ServiceDefinition

use of org.apache.knox.gateway.service.definition.ServiceDefinition in project knox by apache.

the class ServiceDefinitionsLoader method loadServiceDefinitions.

public static Set<ServiceDeploymentContributor> loadServiceDefinitions(File servicesDir) {
    Set<ServiceDeploymentContributor> contributors = new HashSet<>();
    if (servicesDir.exists() && servicesDir.isDirectory()) {
        try {
            JAXBContext context = JAXBContext.newInstance(ServiceDefinition.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            for (File file : getFileList(servicesDir)) {
                try {
                    FileInputStream inputStream = new FileInputStream(file);
                    ServiceDefinition definition = (ServiceDefinition) unmarshaller.unmarshal(inputStream);
                    // look for rewrite rules as a sibling (for now)
                    UrlRewriteRulesDescriptor rewriteRulesDescriptor = loadRewriteRules(file.getParentFile());
                    contributors.add(new ServiceDefinitionDeploymentContributor(definition, rewriteRulesDescriptor));
                    log.addedServiceDefinition(definition.getName(), definition.getRole(), definition.getVersion());
                } catch (FileNotFoundException e) {
                    log.failedToFindServiceDefinitionFile(file.getAbsolutePath(), e);
                }
            }
        } catch (JAXBException e) {
            log.failedToLoadServiceDefinition(SERVICE_FILE_NAME, e);
        }
    }
    return contributors;
}
Also used : ServiceDefinitionDeploymentContributor(org.apache.knox.gateway.deploy.impl.ServiceDefinitionDeploymentContributor) ServiceDeploymentContributor(org.apache.knox.gateway.deploy.ServiceDeploymentContributor) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) UrlRewriteRulesDescriptor(org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) File(java.io.File) ServiceDefinition(org.apache.knox.gateway.service.definition.ServiceDefinition) FileInputStream(java.io.FileInputStream) HashSet(java.util.HashSet)

Example 3 with ServiceDefinition

use of org.apache.knox.gateway.service.definition.ServiceDefinition in project knox by apache.

the class GatewayWebsocketHandler method getMatchedBackendURL.

/**
 * This method looks at the context path and returns the backend websocket
 * url. If websocket url is found it is used as is, or we default to
 * ws://{host}:{port} which might or might not be right.
 *
 * @param
 * @return Websocket backend url
 */
private synchronized String getMatchedBackendURL(final String path) {
    final ServiceRegistry serviceRegistryService = services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
    final ServiceDefinitionRegistry serviceDefinitionService = services.getService(GatewayServices.SERVICE_DEFINITION_REGISTRY);
    /* Filter out the /cluster/topology to get the context we want */
    String[] pathInfo = path.split(REGEX_SPLIT_CONTEXT);
    final ServiceDefEntry entry = serviceDefinitionService.getMatchingService(pathInfo[1]);
    if (entry == null) {
        throw new RuntimeException(String.format("Cannot find service for the given path: %s", path));
    }
    /* Filter out /cluster/topology/service to get endpoint */
    String[] pathService = path.split(REGEX_SPLIT_SERVICE_PATH);
    final File servicesDir = new File(config.getGatewayServicesDir());
    final Set<ServiceDefinition> serviceDefs = ServiceDefinitionsLoader.getServiceDefinitions(servicesDir);
    /* URL used to connect to websocket backend */
    String backendURL = urlFromServiceDefinition(serviceDefs, serviceRegistryService, entry, path);
    StringBuffer backend = new StringBuffer();
    try {
        /* if we do not find websocket URL we default to HTTP */
        if (!StringUtils.containsAny(backendURL, WEBSOCKET_PROTOCOL_STRING, SECURE_WEBSOCKET_PROTOCOL_STRING)) {
            URL serviceUrl = new URL(backendURL);
            /* Use http host:port if ws url not configured */
            final String protocol = (serviceUrl.getProtocol() == "ws" || serviceUrl.getProtocol() == "wss") ? serviceUrl.getProtocol() : "ws";
            backend.append(protocol).append("://");
            backend.append(serviceUrl.getHost()).append(":");
            backend.append(serviceUrl.getPort()).append("/");
            backend.append(serviceUrl.getPath());
        } else {
            URI serviceUri = new URI(backendURL);
            backend.append(serviceUri);
            /* Avoid Zeppelin Regression - as this would require ambari changes and break current knox websocket use case*/
            if (!StringUtils.endsWith(backend.toString(), "/ws") && pathService.length > 0 && pathService[1] != null) {
                backend.append(pathService[1]);
            }
        }
        backendURL = backend.toString();
    } catch (MalformedURLException e) {
        LOG.badUrlError(e);
        throw new RuntimeException(e.toString());
    } catch (Exception e1) {
        LOG.failedCreatingWebSocket(e1);
        throw new RuntimeException(e1.toString());
    }
    return backendURL;
}
Also used : MalformedURLException(java.net.MalformedURLException) ServiceDefEntry(org.apache.knox.gateway.services.registry.ServiceDefEntry) URI(java.net.URI) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) ServiceRegistry(org.apache.knox.gateway.services.registry.ServiceRegistry) File(java.io.File) ServiceDefinition(org.apache.knox.gateway.service.definition.ServiceDefinition) ServiceDefinitionRegistry(org.apache.knox.gateway.services.registry.ServiceDefinitionRegistry)

Example 4 with ServiceDefinition

use of org.apache.knox.gateway.service.definition.ServiceDefinition in project knox by apache.

the class ApplicationDeploymentContributor method loadServiceDefinition.

private static ServiceDefinition loadServiceDefinition(Application application, File file) throws JAXBException, FileNotFoundException, IOException {
    ServiceDefinition definition;
    if (!file.exists()) {
        definition = new ServiceDefinition();
        definition.setName(application.getName());
        List<Route> routes = new ArrayList<Route>(1);
        Route route;
        route = new Route();
        route.setPath("/?**");
        routes.add(route);
        route = new Route();
        route.setPath("/**?**");
        routes.add(route);
        definition.setRoutes(routes);
    } else {
        JAXBContext context = JAXBContext.newInstance(ServiceDefinition.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        try (FileInputStream inputStream = new FileInputStream(file)) {
            definition = (ServiceDefinition) unmarshaller.unmarshal(inputStream);
        }
    }
    return definition;
}
Also used : ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) ServiceDefinition(org.apache.knox.gateway.service.definition.ServiceDefinition) Route(org.apache.knox.gateway.service.definition.Route) FileInputStream(java.io.FileInputStream)

Example 5 with ServiceDefinition

use of org.apache.knox.gateway.service.definition.ServiceDefinition in project knox by apache.

the class ServiceDefinitionsLoader method getServiceDefinitions.

public static Set<ServiceDefinition> getServiceDefinitions(File servicesDir) {
    Set<ServiceDefinition> definitions = new HashSet<>();
    try {
        JAXBContext context = JAXBContext.newInstance(ServiceDefinition.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        for (File f : getFileList(servicesDir)) {
            ServiceDefinition definition = (ServiceDefinition) unmarshaller.unmarshal(f);
            definitions.add(definition);
        }
    } catch (JAXBException e) {
        log.failedToLoadServiceDefinition(SERVICE_FILE_NAME, e);
    }
    return definitions;
}
Also used : JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) ServiceDefinition(org.apache.knox.gateway.service.definition.ServiceDefinition) File(java.io.File) HashSet(java.util.HashSet)

Aggregations

ServiceDefinition (org.apache.knox.gateway.service.definition.ServiceDefinition)7 File (java.io.File)5 ArrayList (java.util.ArrayList)3 JAXBContext (javax.xml.bind.JAXBContext)3 Unmarshaller (javax.xml.bind.Unmarshaller)3 Route (org.apache.knox.gateway.service.definition.Route)3 FileInputStream (java.io.FileInputStream)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 JAXBException (javax.xml.bind.JAXBException)2 UrlRewriteRulesDescriptor (org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor)2 FileNotFoundException (java.io.FileNotFoundException)1 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 List (java.util.List)1 GatewayConfig (org.apache.knox.gateway.config.GatewayConfig)1 DeploymentContext (org.apache.knox.gateway.deploy.DeploymentContext)1 ServiceDeploymentContributor (org.apache.knox.gateway.deploy.ServiceDeploymentContributor)1