Search in sources :

Example 1 with Rule

use of io.fabric8.service.jclouds.firewall.Rule in project fabric8 by jboss-fuse.

the class CloudContainerInstallationTask method install.

public CreateJCloudsContainerMetadata install() {
    LoginCredentials credentials = nodeMetadata.getCredentials();
    // For some cloud providers return do not allow shell access to root, so the user needs to be overrided.
    if (!Strings.isNullOrEmpty(options.getUser()) && credentials != null) {
        credentials = credentials.toBuilder().user(options.getUser()).build();
    } else {
        credentials = nodeMetadata.getCredentials();
    }
    String id = nodeMetadata.getId();
    Set<String> publicAddresses = nodeMetadata.getPublicAddresses();
    // Make a copy of the addresses, because we don't want to return back a guice implementation of Set.
    Set<String> copyOfPublicAddresses = new HashSet<String>();
    for (String publicAddress : publicAddresses) {
        copyOfPublicAddresses.add(publicAddress);
    }
    CreateJCloudsContainerMetadata jCloudsContainerMetadata = new CreateJCloudsContainerMetadata();
    jCloudsContainerMetadata.setCreateOptions(options);
    jCloudsContainerMetadata.setNodeId(nodeMetadata.getId());
    jCloudsContainerMetadata.setContainerName(containerName);
    jCloudsContainerMetadata.setPublicAddresses(copyOfPublicAddresses);
    jCloudsContainerMetadata.setHostname(nodeMetadata.getHostname());
    if (credentials != null) {
        jCloudsContainerMetadata.setIdentity(credentials.identity);
        jCloudsContainerMetadata.setCredential(credentials.credential);
    }
    String publicAddress = "";
    Properties addresses = new Properties();
    if (publicAddresses != null && !publicAddresses.isEmpty()) {
        publicAddress = publicAddresses.iterator().next();
        addresses.put(ZkDefs.PUBLIC_IP, publicAddress);
    }
    options.getSystemProperties().put(ContainerProviderUtils.ADDRESSES_PROPERTY_KEY, addresses);
    options.getMetadataMap().put(containerName, jCloudsContainerMetadata);
    // Setup firwall for node
    try {
        FirewallManager firewallManager = firewallManagerFactory.getFirewallManager(computeService);
        if (firewallManager.isSupported()) {
            listener.onStateChange("Configuring firewall.");
            String source = getOriginatingIp();
            Rule httpRule = Rule.create().source("0.0.0.0/0").destination(nodeMetadata).port(8181);
            firewallManager.addRules(httpRule);
            if (source != null) {
                Rule jmxRule = Rule.create().source(source).destination(nodeMetadata).ports(44444, 1099);
                Rule sshRule = Rule.create().source(source).destination(nodeMetadata).port(8101);
                Rule zookeeperRule = Rule.create().source(source).destination(nodeMetadata).port(2181);
                firewallManager.addRules(jmxRule, sshRule, zookeeperRule);
            }
            // where firewall configuration is shared among nodes of the same groups, e.g. EC2.
            if (!Strings.isNullOrEmpty(publicAddress)) {
                Rule zookeeperFromTargetRule = Rule.create().source(publicAddress + "/32").destination(nodeMetadata).port(2181);
                firewallManager.addRule(zookeeperFromTargetRule);
            }
        } else {
            listener.onStateChange(String.format("Skipping firewall configuration. Not supported for provider %s", options.getProviderName()));
        }
    } catch (FirewallNotSupportedOnProviderException e) {
        LOGGER.warn("Firewall manager not supported. Firewall will have to be manually configured.");
    } catch (IOException e) {
        LOGGER.warn("Could not lookup originating ip. Firewall will have to be manually configured.", e);
    } catch (Throwable t) {
        LOGGER.warn("Failed to setup firewall", t);
    }
    try {
        String script = buildInstallAndStartScript(containerName, options);
        listener.onStateChange(String.format("Installing fabric agent on container %s. It may take a while...", containerName));
        ExecResponse response = null;
        String uploadPath = "/tmp/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip";
        URL distributionURL = options.getProxyUri().resolve("io/fabric8/fabric8-karaf/" + FabricConstants.FABRIC_VERSION + "/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip").toURL();
        try {
            if (options.doUploadDistribution()) {
                uploadToNode(computeService.getContext(), nodeMetadata, credentials, distributionURL, uploadPath);
            }
            if (credentials != null) {
                response = computeService.runScriptOnNode(id, script, templateOptions.overrideLoginCredentials(credentials).runAsRoot(false));
            } else {
                response = computeService.runScriptOnNode(id, script, templateOptions);
            }
        } catch (AuthorizationException ex) {
            throw new Exception("Failed to connect to the container via ssh.");
        } catch (SshException ex) {
            throw new Exception("Failed to connect to the container via ssh.");
        }
        if (response != null && response.getOutput() != null) {
            if (response.getOutput().contains(ContainerProviderUtils.FAILURE_PREFIX)) {
                jCloudsContainerMetadata.setFailure(new Exception(ContainerProviderUtils.parseScriptFailure(response.getOutput())));
            }
            String overridenResolverValue = ContainerProviderUtils.parseResolverOverride(response.getOutput());
            if (overridenResolverValue != null) {
                jCloudsContainerMetadata.setOverridenResolver(overridenResolverValue);
                listener.onStateChange("Overriding resolver to " + overridenResolverValue + ".");
            }
        } else {
            jCloudsContainerMetadata.setFailure(new Exception("No response received for fabric install script."));
        }
    } catch (Throwable t) {
        jCloudsContainerMetadata.setFailure(t);
    }
    // Cleanup addresses.
    options.getSystemProperties().clear();
    return jCloudsContainerMetadata;
}
Also used : FirewallManager(io.fabric8.service.jclouds.firewall.FirewallManager) ExecResponse(org.jclouds.compute.domain.ExecResponse) AuthorizationException(org.jclouds.rest.AuthorizationException) FirewallNotSupportedOnProviderException(io.fabric8.service.jclouds.firewall.FirewallNotSupportedOnProviderException) IOException(java.io.IOException) SshException(org.jclouds.ssh.SshException) Properties(java.util.Properties) URL(java.net.URL) AuthorizationException(org.jclouds.rest.AuthorizationException) FirewallNotSupportedOnProviderException(io.fabric8.service.jclouds.firewall.FirewallNotSupportedOnProviderException) IOException(java.io.IOException) SshException(org.jclouds.ssh.SshException) LoginCredentials(org.jclouds.domain.LoginCredentials) Rule(io.fabric8.service.jclouds.firewall.Rule) HashSet(java.util.HashSet)

Example 2 with Rule

use of io.fabric8.service.jclouds.firewall.Rule in project fabric8 by jboss-fuse.

the class CloudFirewallEdit method doExecute.

@Override
protected Object doExecute() throws Exception {
    if (validateArguments()) {
        ComputeService computeService = findTargetComputeService();
        if (computeService == null) {
            return null;
        }
        Set<String> sourceCidrs = collectCirds();
        FirewallManager firewallManager = firewallManagerFactory.getFirewallManager(computeService);
        NodeMetadata node = null;
        if (!Strings.isNullOrEmpty(targetContainerName) && getCurator().getZookeeperClient().isConnected() && fabricService != null) {
            CreateJCloudsContainerMetadata metadata = getContainerCloudMetadata(targetContainerName);
            if (metadata != null && !Strings.isNullOrEmpty(metadata.getNodeId())) {
                targetNodeId = metadata.getNodeId();
            }
        }
        if (!Strings.isNullOrEmpty(targetNodeId)) {
            node = computeService.getNodeMetadata(targetNodeId);
        }
        if (node == null) {
            System.err.println("Could not find target node. Make sure you specified either --target-node-id or --target-container using a valid cloud container.");
            return null;
        }
        if (flush) {
            firewallManager.addRule(Rule.create().destination(node).flush());
            return null;
        }
        for (String cidr : sourceCidrs) {
            Rule rule = Rule.create().destination(node).source(cidr);
            if (port != null && port.length > 0) {
                rule = rule.ports(port);
            }
            if (revoke) {
                firewallManager.addRule(rule.revoke());
            } else {
                firewallManager.addRule(rule);
            }
        }
    }
    return null;
}
Also used : NodeMetadata(org.jclouds.compute.domain.NodeMetadata) FirewallManager(io.fabric8.service.jclouds.firewall.FirewallManager) CreateJCloudsContainerMetadata(io.fabric8.service.jclouds.CreateJCloudsContainerMetadata) Rule(io.fabric8.service.jclouds.firewall.Rule) ComputeService(org.jclouds.compute.ComputeService)

Example 3 with Rule

use of io.fabric8.service.jclouds.firewall.Rule in project fabric8 by jboss-fuse.

the class JsonRuleBaseReaderTest method parseWithCookiePath.

@Test
public void parseWithCookiePath() throws Exception {
    final InputStream in = JsonRuleBaseBuilder.newRuleBase().rule("/foo/{path}", "https://foo.com/cheese/{path}", "/cookiePath").inputStream();
    final Map<String, HttpProxyRule> rules = JsonRuleBaseReader.parseJson(in);
    final HttpProxyRule httpProxyRule = rules.get("/foo/{path}");
    assertThat(httpProxyRule.getCookiePath(), equalTo("/cookiePath"));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule) Test(org.junit.Test)

Example 4 with Rule

use of io.fabric8.service.jclouds.firewall.Rule in project fabric8 by jboss-fuse.

the class HttpMappingRuleConfiguration method updateConfiguration.

private void updateConfiguration(Map<String, ?> configuration) throws Exception {
    LOG.info("activating http mapping rule " + configuration);
    configurer.configure(configuration, this);
    LOG.info("activating http mapping rule " + zooKeeperPath + " on " + gateway.get().getPort());
    String zkPath = getZooKeeperPath();
    Objects.notNull(zkPath, "zooKeeperPath");
    Objects.notNull(getUriTemplate(), "uriTemplate");
    LoadBalancer loadBalancer = LoadBalancers.createLoadBalancer(loadBalancerType, stickyLoadBalancerCacheSize);
    LOG.info("activating http mapping ZooKeeper path: " + zkPath + " with URI template: " + uriTemplate + " enabledVersion: " + enabledVersion + " with load balancer: " + loadBalancer);
    if (httpMappingRuleBase != null) {
        gateway.get().removeMappingRuleConfiguration(httpMappingRuleBase);
    }
    httpMappingRuleBase = new HttpMappingRuleBase(new SimplePathTemplate(uriTemplate), gateway.get().getGatewayVersion(), enabledVersion, loadBalancer, reverseHeaders);
    mappingTree = new HttpMappingZooKeeperTreeCache(curator.get(), httpMappingRuleBase, zooKeeperPath);
    mappingTree.init();
    gateway.get().addMappingRuleConfiguration(httpMappingRuleBase);
}
Also used : HttpMappingZooKeeperTreeCache(io.fabric8.gateway.fabric.support.http.HttpMappingZooKeeperTreeCache) HttpMappingRuleBase(io.fabric8.gateway.fabric.support.http.HttpMappingRuleBase) SimplePathTemplate(io.fabric8.zookeeper.internal.SimplePathTemplate) LoadBalancer(io.fabric8.gateway.loadbalancer.LoadBalancer)

Example 5 with Rule

use of io.fabric8.service.jclouds.firewall.Rule in project fabric8 by jboss-fuse.

the class HttpMappingRuleBase method updateMappingRules.

/**
 * Given a path being added or removed, update the services.
 *
 * @param remove        whether to remove (if true) or add (if false) this mapping
 * @param path          the path that this mapping is bound
 * @param services      the HTTP URLs of the services to map to
 * @param defaultParams the default parameters to use in the URI templates such as for version and container
 * @param serviceDetails
 */
public void updateMappingRules(boolean remove, String path, List<String> services, Map<String, String> defaultParams, ServiceDetails serviceDetails) {
    SimplePathTemplate pathTemplate = getUriTemplate();
    if (pathTemplate != null) {
        boolean versionSpecificUri = pathTemplate.getParameterNames().contains("version");
        String versionId = defaultParams.get("version");
        if (!remove && Strings.isNotBlank(versionId) && !versionSpecificUri && gatewayVersion != null) {
            // lets ignore this mapping if the version does not match
            if (!gatewayVersion.equals(versionId)) {
                remove = true;
            }
        }
        Map<String, String> params = new HashMap<String, String>();
        if (defaultParams != null) {
            params.putAll(defaultParams);
        }
        params.put("servicePath", path);
        if (!versionSpecificUri && Strings.isNotBlank(this.enabledVersion)) {
            if (!serviceDetails.getVersion().equals(this.enabledVersion)) {
                remove = true;
            }
        }
        for (String service : services) {
            populateUrlParams(params, service);
            String fullPath = pathTemplate.bindByNameNonStrict(params);
            if (remove) {
                MappedServices rule = mappingRules.get(fullPath);
                if (rule != null) {
                    List<String> serviceUrls = rule.getServiceUrls();
                    serviceUrls.remove(service);
                    if (serviceUrls.isEmpty()) {
                        mappingRules.remove(fullPath);
                    }
                }
            } else {
                MappedServices mappedServices = new MappedServices(service, serviceDetails, loadBalancer, reverseHeaders);
                MappedServices oldRule = mappingRules.put(fullPath, mappedServices);
                if (oldRule != null) {
                    mappedServices.getServiceUrls().addAll(oldRule.getServiceUrls());
                }
            }
        }
    }
    fireMappingRulesChanged();
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MappedServices(io.fabric8.gateway.handlers.http.MappedServices) SimplePathTemplate(io.fabric8.zookeeper.internal.SimplePathTemplate)

Aggregations

HttpProxyRule (io.fabric8.gateway.model.HttpProxyRule)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 InputStream (java.io.InputStream)5 Test (org.junit.Test)4 IOException (java.io.IOException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 MappedServices (io.fabric8.gateway.handlers.http.MappedServices)2 HTTPIngressPath (io.fabric8.kubernetes.api.model.extensions.HTTPIngressPath)2 HTTPIngressRuleValue (io.fabric8.kubernetes.api.model.extensions.HTTPIngressRuleValue)2 Ingress (io.fabric8.kubernetes.api.model.extensions.Ingress)2 IngressBackend (io.fabric8.kubernetes.api.model.extensions.IngressBackend)2 IngressRule (io.fabric8.kubernetes.api.model.extensions.IngressRule)2 IngressSpec (io.fabric8.kubernetes.api.model.extensions.IngressSpec)2 FirewallManager (io.fabric8.service.jclouds.firewall.FirewallManager)2 Rule (io.fabric8.service.jclouds.firewall.Rule)2 SimplePathTemplate (io.fabric8.zookeeper.internal.SimplePathTemplate)2 HashMap (java.util.HashMap)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1