Example usage for com.amazonaws.services.elasticloadbalancing.model LoadBalancerDescription getListenerDescriptions

List of usage examples for com.amazonaws.services.elasticloadbalancing.model LoadBalancerDescription getListenerDescriptions

Introduction

In this page you can find the example usage for com.amazonaws.services.elasticloadbalancing.model LoadBalancerDescription getListenerDescriptions.

Prototype


public java.util.List<ListenerDescription> getListenerDescriptions() 

Source Link

Document

The listeners for the load balancer.

Usage

From source file:com.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.ElbDetail.java

License:Open Source License

private void buildUI(DescribeLoadBalancersResult detail) {

    JTabbedPane tabs = new JTabbedPane();

    tabs.add("Load Balancer", primaryScrollPane);

    final JTable healthCheckTable = new JTable(healthCheckTableModel);
    JScrollPane healthCheckScrollPane = new JScrollPane(healthCheckTable);
    tabs.add("Health Check", healthCheckScrollPane);

    final JTable listenersTable = new JTable(listenersTableModel);
    JScrollPane listenersScrollPane = new JScrollPane(listenersTable);
    tabs.add("Listeners", listenersScrollPane);

    this.add(tabs, BorderLayout.CENTER);

    List<LoadBalancerDescription> elbs = detail.getLoadBalancerDescriptions();
    if (!elbs.isEmpty()) {

        LoadBalancerDescription elb = elbs.get(0);

        if (!elb.getAvailabilityZones().isEmpty()) {

            StringBuilder azs = new StringBuilder();
            for (String az : elb.getAvailabilityZones()) {
                azs.append(az).append(", ");
            }/*  w  w  w  . j ava2s .c o m*/

            primaryTableModel.addRow(new Object[] { "Availability Zones", azs.toString() });
        }

        if (elb.getCanonicalHostedZoneName() != null) {
            primaryTableModel
                    .addRow(new Object[] { "Canonical Hosted Zone name", elb.getCanonicalHostedZoneName() });
        }
        if (elb.getCanonicalHostedZoneNameID() != null) {
            primaryTableModel.addRow(
                    new Object[] { "Canonical Hosted Zone name Id", elb.getCanonicalHostedZoneNameID() });
        }
        if (elb.getCreatedTime() != null) {
            primaryTableModel.addRow(new Object[] { "Created", elb.getCreatedTime() });
        }
        if (elb.getDNSName() != null) {
            primaryTableModel.addRow(new Object[] { "DNS Name", elb.getDNSName() });
        }

        if (!elb.getInstances().isEmpty()) {

            StringBuilder instances = new StringBuilder();
            for (Instance instance : elb.getInstances()) {
                instances.append(instance.getInstanceId()).append(", ");
            }

            primaryTableModel.addRow(new Object[] { "Instances", instances.toString() });
        }

        if (elb.getLoadBalancerName() != null) {
            primaryTableModel.addRow(new Object[] { "Load Balander Name", elb.getLoadBalancerName() });
        }
        if (elb.getScheme() != null) {
            primaryTableModel.addRow(new Object[] { "Scheme", elb.getScheme() });
        }

        if (!elb.getSecurityGroups().isEmpty()) {

            StringBuilder sgs = new StringBuilder();
            for (String sg : elb.getSecurityGroups()) {
                sgs.append(sg).append(", ");
            }

            primaryTableModel.addRow(new Object[] { "Security Groups", sgs.toString() });
        }

        if (elb.getSourceSecurityGroup() != null) {
            primaryTableModel.addRow(
                    new Object[] { "Source Security Group", elb.getSourceSecurityGroup().getGroupName() });
        }

        if (!elb.getSubnets().isEmpty()) {

            StringBuilder subnets = new StringBuilder();
            for (String subnet : elb.getSubnets()) {
                subnets.append(subnet).append(", ");
            }

            primaryTableModel.addRow(new Object[] { "Subnets", subnets.toString() });
        }

        if (elb.getVPCId() != null) {
            primaryTableModel.addRow(new Object[] { "VPC Id", elb.getVPCId() });
        }

        /**
         * Health Check
         */

        healthCheckTableModel.addColumn("Property");
        healthCheckTableModel.addColumn("Value");

        HealthCheck healthCheck = elb.getHealthCheck();
        if (healthCheck.getHealthyThreshold() != null) {
            healthCheckTableModel.addRow(new Object[] { "Threshold", healthCheck.getHealthyThreshold() });
        }
        if (healthCheck.getInterval() != null) {
            healthCheckTableModel.addRow(new Object[] { "Interval", healthCheck.getInterval() });
        }
        if (healthCheck.getTarget() != null) {
            healthCheckTableModel.addRow(new Object[] { "Target", healthCheck.getTarget() });
        }
        if (healthCheck.getTimeout() != null) {
            healthCheckTableModel.addRow(new Object[] { "Timeout", healthCheck.getTimeout() });
        }
        if (healthCheck.getUnhealthyThreshold() != null) {
            healthCheckTableModel
                    .addRow(new Object[] { "Unhealth Threshold", healthCheck.getUnhealthyThreshold() });
        }

        /**
         * Listeners
         */

        listenersTableModel.addColumn("Instance Port");
        listenersTableModel.addColumn("Instance Protocol");
        listenersTableModel.addColumn("Load Balancer Port");
        listenersTableModel.addColumn("Load Balancer Protocol");
        listenersTableModel.addColumn("SSL Certificate Id");

        List<ListenerDescription> listenerDescriptions = elb.getListenerDescriptions();
        for (ListenerDescription description : listenerDescriptions) {

            Listener listener = description.getListener();

            String ssl = "";
            if (listener.getSSLCertificateId() != null) {
                ssl = listener.getSSLCertificateId();
            }

            listenersTableModel
                    .addRow(new Object[] { listener.getInstancePort(), listener.getInstanceProtocol(),
                            listener.getLoadBalancerPort(), listener.getProtocol(), ssl });
        }
    }
}

From source file:com.kixeye.chassis.bootstrap.aws.ServerInstanceContext.java

License:Apache License

private ListenerDescription getExhibitorListenerDescription(LoadBalancerDescription loadBalancer) {
    for (ListenerDescription listenerDescription : loadBalancer.getListenerDescriptions()) {
        if (listenerDescription.getListener().getProtocol().toLowerCase().equals("http")) {
            return listenerDescription;
        }/*w w  w  .ja  va2  s  . co  m*/
    }

    throw new BootstrapException(
            "Unable to find any listeners which supports http on ELB " + loadBalancer.getLoadBalancerName());
}

From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java

License:Apache License

public List<Listener> getListeners(LoadBalancerDescription sourceLoadBalancer,
        MigrateLoadBalancerResult result) {
    List<Listener> unmigratableListeners = sourceLoadBalancer.getListenerDescriptions().stream()
            .map(ListenerDescription::getListener).filter(listenerCannotBeMigrated(source, target))
            .collect(Collectors.toList());

    unmigratableListeners.forEach(l -> result.getWarnings()
            .add("The following listeners could not be created: " + l.getProtocol() + ":"
                    + l.getLoadBalancerPort() + " => " + l.getInstanceProtocol() + ":" + l.getInstancePort()
                    + " (certificate: " + l.getSSLCertificateId() + ")."));

    List<Listener> listeners = sourceLoadBalancer.getListenerDescriptions().stream()
            .map(ListenerDescription::getListener).filter(l -> l.getInstancePort() > 0) // strip out invalid load balancer listeners from legacy ELBs
            .collect(Collectors.toList());

    listeners.removeAll(unmigratableListeners);
    return listeners;
}

From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java

License:Apache License

public LoadBalancerAttributes getLoadBalancerAttributes(LoadBalancerDescription sourceLoadBalancer,
        AmazonElasticLoadBalancing sourceClient) {
    LoadBalancerAttributes sourceAttributes = sourceClient
            .describeLoadBalancerAttributes(new DescribeLoadBalancerAttributesRequest()
                    .withLoadBalancerName(sourceLoadBalancer.getLoadBalancerName()))
            .getLoadBalancerAttributes();
    if (sourceLoadBalancer.getListenerDescriptions().stream()
            .anyMatch(l -> l.getListener().getInstancePort() == 0)) {
        sourceAttributes.setCrossZoneLoadBalancing(new CrossZoneLoadBalancing().withEnabled(true));
    }/*  ww w .jav a  2 s. co  m*/
    return sourceAttributes;
}

From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java

License:Apache License

/**
 * Applies any listener policies from the source load balancer to the target load balancer.
 *
 * Since policy names are unique to each load balancer, two policies with the same name in different load balancers
 * may contain different policy attributes. For the sake of simplicity, we assume that policies with the same name
 * are structurally the same, and do not attempt to reconcile any differences between attributes.
 *
 * We will, however, attempt to override the policies applied to a given listener if it's different, e.g., if the
 * source load balancer has policy "a" on port 7000, and the target load balancer has policy "b" on port 7000, we
 * will://  w w w  . ja  va2 s.c o  m
 *   1. create policy "a" if it doesn't exist on the target load balancer, then
 *   2. update the target load balancer so port 7000 will have only policy "a"
 */
public void applyListenerPolicies(AmazonElasticLoadBalancing sourceClient,
        AmazonElasticLoadBalancing targetClient, LoadBalancerDescription source, String loadBalancerName) {
    Set<String> policiesToRetrieve = new HashSet<>();
    Map<String, String> policyNameMap = new HashMap<>();
    source.getListenerDescriptions().forEach(d -> policiesToRetrieve.addAll(d.getPolicyNames()));
    List<PolicyDescription> sourcePolicies = sourceClient
            .describeLoadBalancerPolicies(new DescribeLoadBalancerPoliciesRequest()
                    .withLoadBalancerName(source.getLoadBalancerName()).withPolicyNames(policiesToRetrieve))
            .getPolicyDescriptions();
    List<PolicyDescription> targetPolicies = targetClient
            .describeLoadBalancerPolicies(
                    new DescribeLoadBalancerPoliciesRequest().withLoadBalancerName(loadBalancerName))
            .getPolicyDescriptions();

    sourcePolicies.forEach(p -> {
        Optional<PolicyDescription> match = targetPolicies.stream().filter(
                tp -> tp.getPolicyAttributeDescriptions().size() == p.getPolicyAttributeDescriptions().size()
                        && tp.getPolicyAttributeDescriptions().containsAll(p.getPolicyAttributeDescriptions()))
                .findFirst();

        if (match.isPresent()) {
            policyNameMap.put(p.getPolicyName(), match.get().getPolicyName());
        } else {
            String policyName = p.getPolicyName();
            if (policyName.startsWith("ELBSample-") || policyName.startsWith("ELBSecurityPolicy-")) {
                policyName = "migrated-" + policyName;
            }
            policyNameMap.put(p.getPolicyName(), policyName);
            CreateLoadBalancerPolicyRequest request = new CreateLoadBalancerPolicyRequest()
                    .withPolicyName(policyName).withLoadBalancerName(loadBalancerName)
                    .withPolicyTypeName(p.getPolicyTypeName());
            // only copy policy attributes if this is not a pre-defined policy
            // (as defined by the presence of 'Reference-Security-Policy'
            Optional<PolicyAttributeDescription> referencePolicy = p.getPolicyAttributeDescriptions().stream()
                    .filter(d -> d.getAttributeName().equals("Reference-Security-Policy")).findFirst();
            if (referencePolicy.isPresent()) {
                request.withPolicyAttributes(new PolicyAttribute(referencePolicy.get().getAttributeName(),
                        referencePolicy.get().getAttributeValue()));
            } else {
                request.withPolicyAttributes(p.getPolicyAttributeDescriptions().stream()
                        .map(d -> new PolicyAttribute(d.getAttributeName(), d.getAttributeValue()))
                        .collect(Collectors.toList()));
            }
            targetClient.createLoadBalancerPolicy(request);
        }
    });
    source.getListenerDescriptions().forEach(l -> targetClient.setLoadBalancerPoliciesOfListener(
            new SetLoadBalancerPoliciesOfListenerRequest().withLoadBalancerName(loadBalancerName)
                    .withLoadBalancerPort(l.getListener().getLoadBalancerPort()).withPolicyNames(
                            l.getPolicyNames().stream().map(policyNameMap::get).collect(Collectors.toList()))));
}

From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java

License:Apache License

/**
 * Creates the app specific security group, or returns the ID of one if it already exists
 *
 * @param appGroups               list of existing security groups in which to look for existing app security group
 * @param elbGroup                the elb specific security group, which will allow ingress permission from the
 *                                app specific security group
 *//*from w  ww . ja  va  2  s.co  m*/
protected void buildApplicationSecurityGroup(LoadBalancerDescription sourceDescription,
        List<SecurityGroup> appGroups, MigrateSecurityGroupResult elbGroup) {
    if (getDeployDefaults().getAddAppGroupToServerGroup()) {
        AmazonEC2 targetAmazonEC2 = getAmazonClientProvider().getAmazonEC2(target.getCredentials(),
                target.getRegion(), true);
        Optional<SecurityGroup> existing = appGroups.stream().filter(isAppSecurityGroup()).findFirst();
        MigrateSecurityGroupReference appGroupReference = new MigrateSecurityGroupReference();
        appGroupReference.setAccountId(target.getCredentials().getAccountId());
        appGroupReference.setVpcId(target.getVpcId());
        appGroupReference.setTargetName(applicationName);
        if (existing.isPresent()) {
            elbGroup.getReused().add(appGroupReference);
        } else {
            elbGroup.getCreated().add(appGroupReference);
            if (!dryRun) {
                UpsertSecurityGroupDescription upsertDescription = new UpsertSecurityGroupDescription();
                upsertDescription.setDescription("Application security group for " + applicationName);
                upsertDescription.setName(applicationName);
                upsertDescription.setVpcId(target.getVpcId());
                upsertDescription.setRegion(target.getRegion());
                upsertDescription.setCredentials(target.getCredentials());
                getTask().updateStatus(LoadBalancerMigrator.BASE_PHASE,
                        "Creating security group " + upsertDescription.getName() + " in "
                                + target.getCredentialAccount() + "/" + target.getRegion() + "/"
                                + target.getVpcId());
                String newGroupId = targetLookup.createSecurityGroup(upsertDescription).getSecurityGroup()
                        .getGroupId();
                // After the create request completes, there is a brief period where the security group might not be
                // available and subsequent operations on it will fail, so make sure it's there
                OperationPoller.retryWithBackoff(o -> appGroups.addAll(targetAmazonEC2
                        .describeSecurityGroups(new DescribeSecurityGroupsRequest().withGroupIds(newGroupId))
                        .getSecurityGroups()), 200, 5);
            }
        }
        if (!dryRun) {
            String elbGroupId = elbGroup.getTarget().getTargetId();
            SecurityGroup appGroup = appGroups.stream().filter(isAppSecurityGroup()).findFirst().get();
            if (allowIngressFromClassic) {
                addClassicLinkIngress(targetLookup, getDeployDefaults().getClassicLinkSecurityGroupName(),
                        appGroup.getGroupId(), target.getCredentials(), target.getVpcId());
            }
            boolean hasElbIngressPermission = appGroup.getIpPermissions().stream().anyMatch(
                    p -> p.getUserIdGroupPairs().stream().anyMatch(u -> u.getGroupId().equals(elbGroupId)));
            if (!hasElbIngressPermission) {
                sourceDescription.getListenerDescriptions().forEach(l -> {
                    Listener listener = l.getListener();
                    IpPermission newPermission = new IpPermission().withIpProtocol("tcp")
                            .withFromPort(listener.getInstancePort()).withToPort(listener.getInstancePort())
                            .withUserIdGroupPairs(
                                    new UserIdGroupPair().withGroupId(elbGroupId).withVpcId(target.getVpcId()));
                    targetAmazonEC2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest()
                            .withGroupId(appGroup.getGroupId()).withIpPermissions(newPermission));
                });
            }
        }
    }
}

From source file:com.netflix.spinnaker.clouddriver.aws.deploy.handlers.MigrateLoadBalancerStrategy.java

License:Apache License

private void addPublicIngress(AmazonEC2 targetAmazonEC2, String elbGroupId,
        LoadBalancerDescription sourceDescription) {
    List<IpPermission> permissions = sourceDescription.getListenerDescriptions().stream()
            .map(l -> new IpPermission().withIpProtocol("tcp")
                    .withFromPort(l.getListener().getLoadBalancerPort())
                    .withToPort(l.getListener().getLoadBalancerPort()).withIpRanges("0.0.0.0/0"))
            .collect(Collectors.toList());

    targetAmazonEC2.authorizeSecurityGroupIngress(
            new AuthorizeSecurityGroupIngressRequest().withGroupId(elbGroupId).withIpPermissions(permissions));
}

From source file:com.proofpoint.discovery.elb.ElasticLoadBalancerUpdater.java

License:Apache License

public void update() throws Exception {
    for (LoadBalancerDescription loadBalancer : elbClient.describeLoadBalancers()
            .getLoadBalancerDescriptions()) {
        // split ELB name into parts
        String elbName = loadBalancer.getLoadBalancerName();
        List<String> parts = copyOf(Splitter.on('-').split(elbName).iterator());
        if (parts.size() != 3 && parts.size() != 4) {
            log.debug("ignoring load balancer: %s", elbName);
            continue;
        }/*from   ww  w.ja v  a  2s .co  m*/
        String environment = parts.get(0);
        String type = parts.get(1);
        String pool = parts.get(2);
        log.debug("found load balancer: %s", elbName);

        // check against environment
        if (!environment.equals(nodeInfo.getEnvironment())) {
            continue;
        }

        // look for services in discovery
        ServiceDescriptors services = discoveryClient.getServices(type, pool).get(1, TimeUnit.SECONDS);

        // map services to instances
        Set<String> instances = newHashSet();
        for (ServiceDescriptor descriptor : services.getServiceDescriptors()) {
            String instanceId = extractEc2InstanceId(descriptor.getLocation());
            if (instanceId == null) {
                log.warn("invalid EC2 location: %s", descriptor.getLocation());
                continue;
            }

            // verify load balancer listeners against the service announcement
            boolean valid = true;
            for (Listener listener : transform(loadBalancer.getListenerDescriptions(), GET_LISTENER)) {
                if (!serviceExistsForListener(listener, descriptor.getProperties())) {
                    valid = false;
                    log.warn("load balancer %s listener %s does not match service %s", elbName, listener,
                            descriptor);
                }
            }
            if (valid) {
                instances.add(instanceId);
            }
        }

        // get registered instances
        Set<String> registeredInstances = newHashSet(transform(loadBalancer.getInstances(), GET_INSTANCE_ID));

        // add new instances to load balancer
        Collection<String> addInstances = difference(instances, registeredInstances);
        if (!addInstances.isEmpty()) {
            registerInstances(elbName, addInstances);
        }

        // remove missing instances from load balancer
        Collection<String> removeInstances = difference(registeredInstances, instances);
        if (!removeInstances.isEmpty()) {
            deregisterInstances(elbName, removeInstances);
        }
    }
}

From source file:com.swap.aws.elb.client.AWSHelper.java

License:Apache License

/**
 * Returns all the listeners attached to the load balancer. Useful while
 * deciding if all the listeners are necessary or some should be removed.
 * /*w  ww . j  av a 2s.c  om*/
 * @param loadBalancerName
 * @return list of instances attached to load balancer
 */
public List<Listener> getAttachedListeners(String loadBalancerName) {
    try {
        LoadBalancerDescription lbDescription = getLoadBalancerDescription(loadBalancerName);

        if (lbDescription == null) {
            log.warn("Could not find description of load balancer " + loadBalancerName);
            return null;
        }

        List<Listener> listeners = new ArrayList<Listener>();

        List<ListenerDescription> listenerDescriptions = lbDescription.getListenerDescriptions();

        for (ListenerDescription listenerDescription : listenerDescriptions) {
            listeners.add(listenerDescription.getListener());
        }

        return listeners;

    } catch (Exception e) {
        log.error("Could not find description of load balancer " + loadBalancerName);
        return null;
    }

}

From source file:com.zotoh.cloudapi.aws.ElasticLoadBalancer.java

License:Open Source License

private LoadBalancer toELB(LoadBalancerDescription desc) {
    LoadBalancer b = null;/*from  w  ww  . j a v  a2 s  . c om*/
    if (desc != null) {
        ProviderContext x = _svc.getCloud().getContext();
        b = new LoadBalancer();

        b.setCreationTimestamp(desc.getCreatedTime().getTime());
        b.setProviderRegionId(x.getRegionId());
        b.setAddressType(LoadBalancerAddressType.DNS);
        b.setCurrentState(LoadBalancerState.ACTIVE);
        b.setProviderOwnerId(x.getAccountNumber());
        b.setName(desc.getLoadBalancerName());
        b.setDescription(b.getName());
        b.setProviderLoadBalancerId(b.getName());
        b.setAddress(desc.getDNSName());

        // zones
        {
            List<String> lst = desc.getAvailabilityZones();
            if (!isNil(lst)) {
                b.setProviderDataCenterIds(lst.toArray(new String[0]));
            }
        }
        // servers
        {
            List<Instance> lst = desc.getInstances();
            List<String> s = LT();
            if (!isNil(lst))
                for (int i = 0; i < lst.size(); ++i) {
                    s.add(lst.get(i).getInstanceId());
                }
            b.setProviderServerIds(s.toArray(new String[0]));
        }
        // listeners/ports
        {
            List<ListenerDescription> lst = desc.getListenerDescriptions();
            List<LbListener> rc = LT();
            int[] pports;
            if (lst != null)
                for (int i = 0; i < lst.size(); ++i) {
                    rc.add(toLis(lst.get(i)));
                }
            b.setListeners(rc.toArray(new LbListener[0]));
            pports = new int[rc.size()];
            for (int i = 0; i < pports.length; ++i) {
                pports[i] = rc.get(i).getPublicPort();
            }
            b.setPublicPorts(pports);
        }

        // unsupported
        desc.getHealthCheck();
        desc.getPolicies();
        desc.getSourceSecurityGroup();
        desc.getCanonicalHostedZoneName();
    }

    return b;
}