com.amazonaws.services.elasticloadbalancing.model.Instance Java Examples

The following examples show how to use com.amazonaws.services.elasticloadbalancing.model.Instance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClassicLoadBalancer.java    From Baragon with Apache License 2.0 6 votes vote down vote up
private List<DeregisterInstancesFromLoadBalancerRequest> deregisterRequests(BaragonGroup group, Collection<BaragonAgentMetadata> agents, List<LoadBalancerDescription> elbs) {
  List<String> agentInstanceIds = agentInstanceIds(agents);
  List<DeregisterInstancesFromLoadBalancerRequest> requests = new ArrayList<>();
  for (LoadBalancerDescription elb : elbs) {
    if (group.getTrafficSources().contains(new TrafficSource(elb.getLoadBalancerName(), TrafficSourceType.CLASSIC, RegisterBy.INSTANCE_ID))) {
      for (Instance instance : elb.getInstances()) {
        if (!agentInstanceIds.contains(instance.getInstanceId()) && canDeregisterAgent(group, instance.getInstanceId())) {
          List<Instance> instanceList = new ArrayList<>(1);
          instanceList.add(instance);
          requests.add(new DeregisterInstancesFromLoadBalancerRequest(elb.getLoadBalancerName(), instanceList));
          LOG.info("Will deregister instance {} from ELB {}", instance.getInstanceId(), elb.getLoadBalancerName());
        }
      }
    }
  }
  return requests;
}
 
Example #2
Source File: ClassicLoadBalancer.java    From Baragon with Apache License 2.0 6 votes vote down vote up
private boolean shouldRegister(BaragonAgentMetadata agent, String elbName, List<LoadBalancerDescription> elbs) {
  Optional<LoadBalancerDescription> matchingElb = Optional.absent();
  for (LoadBalancerDescription elb : elbs) {
    if (elbName.equals(elb.getLoadBalancerName())) {
      matchingElb = Optional.of(elb);
    }
  }
  if (!matchingElb.isPresent()) {
    return false;
  }

  boolean alreadyRegistered = false;
  for (Instance instance : matchingElb.get().getInstances()) {
    if (agent.getEc2().getInstanceId().get().equals(instance.getInstanceId())) {
      alreadyRegistered = true;
    }
  }

  return !alreadyRegistered && (isVpcOk(agent, matchingElb.get()) || !configuration.get().isCheckForCorrectVpc());
}
 
Example #3
Source File: AWSLoadBalancer.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private Boolean updateExistingLoadBalancer(Cluster cluster) {
	Boolean isUpdated=false;
	LoadBalancerInfo loadBalancerInfo = clusterIdToLoadBalancerMap.get(cluster.getClusterId());

	String loadBalancerName = loadBalancerInfo.getName();
	String region = loadBalancerInfo.getRegion();

	// Get all the instances attached - Attach newly added instances to load balancer

	// attachedInstances list is useful in finding out what are the new instances which
	// should be attached to this load balancer.
	List<Instance> attachedInstances = awsHelper.getAttachedInstances(loadBalancerName, region);

	// clusterMembers stores all the members of a cluster.
	Collection<Member> clusterMembers = cluster.getMembers();

	isUpdated= addClusterMembersInfo(clusterMembers, loadBalancerName, region);

	return isUpdated;
}
 
Example #4
Source File: ClassicLoadBalancer.java    From Baragon with Apache License 2.0 6 votes vote down vote up
public AgentCheckInResponse registerInstance(Instance instance, String id, String elbName, BaragonAgentMetadata agent) {
  Optional<String> maybeException = Optional.absent();
  Optional<LoadBalancerDescription> elb = getElb(elbName);
  if (elb.isPresent()) {
    if (isVpcOk(agent, elb.get())) {
      if (!elb.get().getInstances().contains(instance)) {
        checkAZEnabled(agent, elbName, elb.get());
        RegisterInstancesWithLoadBalancerRequest request = new RegisterInstancesWithLoadBalancerRequest(elbName, Arrays.asList(instance));
        elbClient.registerInstancesWithLoadBalancer(request);
        LOG.info("Registered instances {} with ELB {}", request.getInstances(), request.getLoadBalancerName());
      } else {
        LOG.debug("Agent {} already registered with ELB {}", agent.getAgentId(), elbName);
      }
    } else {
      maybeException = Optional.of(String.format("No ELB found for vpc %s", agent.getEc2().getVpcId()));
    }
  }
  return new AgentCheckInResponse(TrafficSourceState.DONE, maybeException, 0L);
}
 
Example #5
Source File: AWSHelper.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Detaches provided instances from the load balancer, associated with some
 * cluster. Useful when instances are removed from the cluster with which
 * this load balancer is associated.
 *
 * @param loadBalancerName
 * @param instances        to be de-registered from load balancer
 * @param region           of the load balancer
 */
public void deregisterInstancesFromLoadBalancer(String loadBalancerName, List<Instance> instances, String region) {

    log.info("De-registering following instance(s) from load balancer "
            + loadBalancerName);

    for (Instance instance : instances) {
        log.info(instance.getInstanceId());
    }

    DeregisterInstancesFromLoadBalancerRequest deregisterInstancesFromLoadBalancerRequest = new DeregisterInstancesFromLoadBalancerRequest(
            loadBalancerName, instances);

    try {
        elbClient.setEndpoint(String.format(
                Constants.ELB_ENDPOINT_URL_FORMAT, region));

        elbClient
                .deregisterInstancesFromLoadBalancer(deregisterInstancesFromLoadBalancerRequest);

    } catch (AmazonClientException e) {
        log.error("Could not de-register instances from load balancer "
                + loadBalancerName, e);
    }
}
 
Example #6
Source File: AWSHelper.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns instances attached to the load balancer. Useful when deciding if
 * all attached instances are required or some should be detached.
 *
 * @param loadBalancerName
 * @param region
 * @return list of instances attached
 */
public List<Instance> getAttachedInstances(String loadBalancerName,
                                           String region) {
    try {
        LoadBalancerDescription lbDescription = getLoadBalancerDescription(loadBalancerName, region);

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

        return lbDescription.getInstances();

    } catch (AmazonClientException e) {
        log.error("Could not find instances attached  load balancer "+ loadBalancerName, e);
    }

    return null;
}
 
Example #7
Source File: ElbManager.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public AgentCheckInResponse attemptAddAgent(BaragonAgentMetadata agent, Optional<BaragonGroup> group, String groupName, boolean isStatusCheck) throws AmazonClientException, NoMatchingElbForVpcException {
  TrafficSourceState state = TrafficSourceState.DONE;
  Optional<String> maybeVpcException = Optional.absent();
  long maxWaitTime = 0L;
  if (isElbEnabledAgent(agent, group, groupName)) {
    boolean anyCompatible = false;
    StringBuilder message = new StringBuilder();
    for (TrafficSource source : group.get().getTrafficSources()) {
      if (source.getRegisterBy() == RegisterBy.PRIVATE_IP && !agent.getEc2().getPrivateIp().isPresent()) {
        message.append(String.format("No private ip present to register by for source %s ", source.getName()));
        continue;
      } else if (source.getRegisterBy() == RegisterBy.INSTANCE_ID && !agent.getEc2().getInstanceId().isPresent()) {
        message.append(String.format("No instance id present to register by for source %s ", source.getName()));
        continue;
      }
      anyCompatible = true;
      String id = source.getRegisterBy() == RegisterBy.PRIVATE_IP ? agent.getEc2().getPrivateIp().get() : agent.getEc2().getInstanceId().get();
      Instance instance = source.getRegisterBy() == RegisterBy.PRIVATE_IP ? null : new Instance(agent.getEc2().getInstanceId().get());
      AgentCheckInResponse response = isStatusCheck ?
          getLoadBalancer(source.getType()).checkRegisteredInstance(instance, id, source, agent) :
          getLoadBalancer(source.getType()).registerInstance(instance, id, source.getName(), agent);
      if (response.getExceptionMessage().isPresent()) {
        maybeVpcException = Optional.of(maybeVpcException.or("") + response.getExceptionMessage().get() + "\n");
      }
      if (response.getState().ordinal() > state.ordinal()) {
        state = response.getState();
      }
      if (response.getWaitTime() > maxWaitTime) {
        maxWaitTime = response.getWaitTime();
      }
    }
    if (maybeVpcException.isPresent() && configuration.get().isFailWhenNoElbForVpc()) {
      throw new NoMatchingElbForVpcException(maybeVpcException.get());
    }
    if (!anyCompatible) {
      return new AgentCheckInResponse(TrafficSourceState.ERROR, Optional.of(message.toString()), maxWaitTime);
    }
  }
  return new AgentCheckInResponse(state, maybeVpcException, maxWaitTime);
}
 
Example #8
Source File: ClassicLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
private List<RegisterInstancesWithLoadBalancerRequest> registerRequests(BaragonGroup group, Collection<BaragonAgentMetadata> agents, List<LoadBalancerDescription> elbs) {
  List<RegisterInstancesWithLoadBalancerRequest> requests = new ArrayList<>();
  for (BaragonAgentMetadata agent : agents) {
    try {
      for (TrafficSource source : group.getTrafficSources()) {
        if (source.getType() != TrafficSourceType.CLASSIC) {
          continue;
        }
        if (agent.getEc2().getInstanceId().isPresent()) {
          if (shouldRegister(agent, source.getName(), elbs)) {
            Instance instance = new Instance(agent.getEc2().getInstanceId().get());
            requests.add(new RegisterInstancesWithLoadBalancerRequest(source.getName(), Arrays.asList(instance)));
            checkAZEnabled(agent, source.getName(), elbs);
            LOG.info("Will register {}-{} with ELB {}", agent.getAgentId(), agent.getEc2().getInstanceId().get(), source.getName());
          } else {
            LOG.debug("Agent {} is already registered", agent);
          }
        } else {
          throw new IllegalArgumentException(String.format("Agent Instance Id must be present to register with an ELB (agent: %s)", agent.getAgentId()));
        }
      }
    } catch (Exception e) {
      LOG.error("Could not create request for BaragonAgent {} due to error: {}", agent, e);
    }
  }
  return requests;
}
 
Example #9
Source File: ClassicLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public AgentCheckInResponse removeInstance(Instance instance, String id, String elbName, String agentId) {
  Optional<LoadBalancerDescription> elb = getElb(elbName);
  if (elb.isPresent()) {
    if (elb.get().getInstances().contains(instance)) {
      DeregisterInstancesFromLoadBalancerRequest request = new DeregisterInstancesFromLoadBalancerRequest(elbName, Arrays.asList(instance));
      elbClient.deregisterInstancesFromLoadBalancer(request);
      LOG.info("Deregistered instance {} from ELB {}", request.getInstances(), request.getLoadBalancerName());
    } else {
      LOG.debug("Agent {} already de-registered from ELB {}", agentId, elbName);
    }
  }
  return new AgentCheckInResponse(TrafficSourceState.DONE, Optional.absent(), 0L);
}
 
Example #10
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
public AgentCheckInResponse checkRegisteredInstance(Instance instance, String id, TrafficSource trafficSource, BaragonAgentMetadata agent) {
  Optional<TargetGroup> maybeTargetGroup = getTargetGroup(trafficSource.getName());
  if (maybeTargetGroup.isPresent()) {
    return instanceHealthResponse(
        new TargetDescription().withId(trafficSource.getRegisterBy() == RegisterBy.INSTANCE_ID ? instance.getInstanceId() : agent.getEc2().getPrivateIp().get()),
        maybeTargetGroup.get(),
        id);
  } else {
    String message = String.format("Could not find target group %s", trafficSource.getName());
    LOG.error(message);
    return new AgentCheckInResponse(TrafficSourceState.ERROR, Optional.of(message), 0L);
  }
}
 
Example #11
Source File: ElbManager.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public AgentCheckInResponse attemptRemoveAgent(BaragonAgentMetadata agent, Optional<BaragonGroup> group, String groupName, boolean isStatusCheck) throws AmazonClientException {
  TrafficSourceState state = TrafficSourceState.DONE;
  long maxWaitTime = 0L;
  Optional<String> maybeExceptions = Optional.absent();
  if (isElbEnabledAgent(agent, group, groupName)) {
    boolean anyCompatible = false;
    StringBuilder message = new StringBuilder();
    for (TrafficSource source : group.get().getTrafficSources()) {
      if (source.getRegisterBy() == RegisterBy.PRIVATE_IP && !agent.getEc2().getPrivateIp().isPresent()) {
        message.append(String.format("No private ip present to register by for source %s ", source.getName()));
        continue;
      } else if (source.getRegisterBy() == RegisterBy.INSTANCE_ID && !agent.getEc2().getInstanceId().isPresent()) {
        message.append(String.format("No instance id present to register by for source %s ", source.getName()));
        continue;
      }
      anyCompatible = true;
      String id = source.getRegisterBy() == RegisterBy.PRIVATE_IP ? agent.getEc2().getPrivateIp().get() : agent.getEc2().getInstanceId().get();
      Instance instance = source.getRegisterBy() == RegisterBy.PRIVATE_IP ? null : new Instance(agent.getEc2().getInstanceId().get());
      AgentCheckInResponse response = isStatusCheck ?
          getLoadBalancer(source.getType()).checkRemovedInstance(id, source.getName(), agent.getAgentId()) :
          getLoadBalancer(source.getType()).removeInstance(instance, id, source.getName(), agent.getAgentId());
      if (response.getState().ordinal() > state.ordinal()) {
        state = response.getState();
      }
      if (response.getExceptionMessage().isPresent()) {
        maybeExceptions = Optional.of(maybeExceptions.or("") + response.getExceptionMessage().get() + "\n");
      }
      if (response.getWaitTime() > maxWaitTime) {
        maxWaitTime = response.getWaitTime();
      }
    }
    if (!anyCompatible) {
      return new AgentCheckInResponse(TrafficSourceState.ERROR, Optional.of(message.toString()), maxWaitTime);
    }
  }
  return new AgentCheckInResponse(state, maybeExceptions, maxWaitTime);
}
 
Example #12
Source File: ElbResource.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/{elbName}/update")
public DeregisterInstancesFromLoadBalancerResult removeFromElb(@PathParam("elbName") String elbName, @QueryParam("instanceId") String instanceId) {
  if (config.isPresent()) {
    DeregisterInstancesFromLoadBalancerRequest request = new DeregisterInstancesFromLoadBalancerRequest(elbName, Arrays.asList(new Instance(instanceId)));
    return elbClient.deregisterInstancesFromLoadBalancer(request);
  } else {
    throw new BaragonWebException("ElbSync and related actions are not currently enabled");
  }
}
 
Example #13
Source File: ElbResource.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/{elbName}/update")
public RegisterInstancesWithLoadBalancerResult addToElb(@PathParam("elbName") String elbName, @QueryParam("instanceId") String instanceId) {
  if (config.isPresent()) {
    RegisterInstancesWithLoadBalancerRequest request = new RegisterInstancesWithLoadBalancerRequest(elbName, Arrays.asList(new Instance(instanceId)));
    return elbClient.registerInstancesWithLoadBalancer(request);
  } else {
    throw new BaragonWebException("ElbSync and related actions are not currently enabled");
  }
}
 
Example #14
Source File: AWSHelper.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Attaches provided instances to the load balancer. Useful when new
 * instances get added to the cluster with which this load balancer is
 * associated.
 *
 * @param loadBalancerName
 * @param instances        to attached to the load balancer
 * @param region           of the load balancer
 */
public void registerInstancesToLoadBalancer(String loadBalancerName,
                                            List<Instance> instances, String region) {

    log.info("Registering following instance(s) to load balancer " + loadBalancerName);

    for (Instance instance : instances) {
        log.info(instance.getInstanceId());
    }

    RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest = new RegisterInstancesWithLoadBalancerRequest(
            loadBalancerName, instances);

    RegisterInstancesWithLoadBalancerResult registerInstancesWithLBRes = null;

    try {
        elbClient.setEndpoint(String.format(
                Constants.ELB_ENDPOINT_URL_FORMAT, region));

        registerInstancesWithLBRes = elbClient
                .registerInstancesWithLoadBalancer(registerInstancesWithLoadBalancerRequest);

    } catch (AmazonClientException e) {
        log.error("Could not register instances to load balancer "
                + loadBalancerName, e);
    }

    if (registerInstancesWithLBRes != null && registerInstancesWithLBRes.getInstances().size() > 0) {
        log.info("Total instances attached to the LB " + loadBalancerName + " : " +
                registerInstancesWithLBRes.getInstances().size());

    }  else {
        log.warn("No instances attached to the LB " + loadBalancerName);
    }
}
 
Example #15
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 4 votes vote down vote up
@Override
public AgentCheckInResponse removeInstance(Instance instance, String id, String trafficSourceName, String agentId) {
  return removeInstance(id, trafficSourceName);
}
 
Example #16
Source File: ClassicLoadBalancer.java    From Baragon with Apache License 2.0 4 votes vote down vote up
public AgentCheckInResponse checkRegisteredInstance(Instance instance, String id, TrafficSource trafficSource, BaragonAgentMetadata agent) {
  return new AgentCheckInResponse(TrafficSourceState.DONE, Optional.absent(), 0L);
}
 
Example #17
Source File: AWSLoadBalancer.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
private Boolean addClusterMembersInfo(Collection<Member> clusterMembers, String loadBalancerName, String region) {
	Boolean isUpdated=false;
	// Register instances in the cluster to load balancer
	List<Instance> instances = new ArrayList<Instance>();
	List<String> availabilityZones = new ArrayList<String>();

	for (Member member : clusterMembers) {
		isUpdated=true;
	    String instanceId = member.getInstanceId();

	    if (log.isDebugEnabled()) {
	        log.debug("Instance " + awsHelper.getAWSInstanceName(instanceId) + " needs to be registered to load balancer "
	                + loadBalancerName);
	    }

	    Instance instance = new Instance();
	    instance.setInstanceId(awsHelper.getAWSInstanceName(instanceId));

	    instances.add(instance);
	    // LB Common Member has a property 'EC2_AVAILABILITY_ZONE' which points to the ec2 availability
	    // zone for this member. Use the property value to update the LB about the relevant zone
	    String availabilityZone = getEC2AvaialbilityZoneOfMember(member);
	    if (availabilityZone != null) {
	        availabilityZones.add(availabilityZone);
	    }

		// add stickiness policy
		if (awsHelper.getAppStickySessionCookie() != null && !awsHelper.getAppStickySessionCookie().isEmpty()) {
			CreateAppCookieStickinessPolicyResult result = awsHelper.createStickySessionPolicy(loadBalancerName, awsHelper.getAppStickySessionCookie(),
			                                                                                   Constants.STICKINESS_POLICY,
			                                                                                   region);

			if (result != null) {
				// Take a single port mapping from a member, and apply the policy for
				// the LB Listener port (Proxy port of the port mapping)
				awsHelper.applyPolicyToLBListenerPorts(member.getPorts(), loadBalancerName,
				                                       Constants.STICKINESS_POLICY, region);
			}
		}

	}

	awsHelper.registerInstancesToLoadBalancer(loadBalancerName, instances, region);

	// update LB with the zones
	if (!availabilityZones.isEmpty() && !AWSExtensionContext.getInstance().isOperatingInVPC()) {
	    awsHelper.addAvailabilityZonesForLoadBalancer(loadBalancerName, availabilityZones, region);
	}
	return isUpdated;
}
 
Example #18
Source File: FetchElasticLoadBalancersJobTest.java    From fullstop with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.violationSinkMock = mock(ViolationSink.class);
    this.clientProviderMock = mock(ClientProvider.class);
    this.accountIdSupplierMock = mock(AccountIdSupplier.class);
    this.jobsPropertiesMock = mock(JobsProperties.class);
    this.portsChecker = mock(PortsChecker.class);
    this.securityGroupsChecker = mock(SecurityGroupsChecker.class);
    this.mockAwsELBClient = mock(AmazonElasticLoadBalancingClient.class);
    this.mockAwsApplications = mock(AwsApplications.class);
    this.mockViolationService = mock(ViolationService.class);
    this.fetchTaupageYamlMock = mock(FetchTaupageYaml.class);
    this.mockAmiDetailsProvider = mock(AmiDetailsProvider.class);
    this.mockEC2InstanceProvider = mock(EC2InstanceProvider.class);

    final Listener listener = new Listener("HTTPS", 80, 80);

    final ListenerDescription listenerDescription = new ListenerDescription();
    listenerDescription.setListener(listener);

    final ArrayList<LoadBalancerDescription> elbs = newArrayList();
    final ArrayList<TagDescription> tagDescriptions = newArrayList();

    final LoadBalancerDescription publicELB = new LoadBalancerDescription();
    publicELB.setScheme("internet-facing");
    publicELB.setListenerDescriptions(newArrayList(listenerDescription));
    publicELB.setCanonicalHostedZoneName("test.com");
    publicELB.setInstances(asList(new Instance("i1"), new Instance("i2")));
    publicELB.setLoadBalancerName("publicELB");
    elbs.add(publicELB);
    tagDescriptions.add(
            new TagDescription()
                    .withLoadBalancerName("publicELB")
                    .withTags(newArrayList(
                            new Tag().withKey("someTag").withValue("someValue"))));

    final LoadBalancerDescription privateELB = new LoadBalancerDescription();
    privateELB.setScheme("internal");
    privateELB.setCanonicalHostedZoneName("internal.org");
    privateELB.setLoadBalancerName("privateELB");
    elbs.add(privateELB);

    for (int i = 1; i <= 20; i++) {
        final String loadBalancerName = "kubeELB" + i;
        final LoadBalancerDescription kubeELB = new LoadBalancerDescription();
        kubeELB.setScheme("internet-facing");
        kubeELB.setCanonicalHostedZoneName("test" + i + ".com");
        kubeELB.setLoadBalancerName(loadBalancerName);
        elbs.add(kubeELB);

        tagDescriptions.add(
                new TagDescription()
                        .withLoadBalancerName(loadBalancerName)
                        .withTags(newArrayList(
                                new Tag().withKey("someTag").withValue("someValue"),
                                new Tag().withKey("kubernetes.io/cluster/").withValue("owned"))));
    }

    mockDescribeELBResult = new DescribeLoadBalancersResult();
    mockDescribeELBResult.setLoadBalancerDescriptions(elbs);

    mockDescribeTagsResult = new DescribeTagsResult();
    mockDescribeTagsResult.setTagDescriptions(tagDescriptions);

    regions.add(REGION1);

    when(clientProviderMock.getClient(any(), any(String.class), any(Region.class))).thenReturn(mockAwsELBClient);

    when(mockEC2InstanceProvider.getById(anyString(), any(Region.class), anyString()))
            .thenReturn(Optional.of(new com.amazonaws.services.ec2.model.Instance().withInstanceId("foo").withImageId("bar")));
    when(mockAmiDetailsProvider.getAmiDetails(anyString(), any(Region.class), anyString()))
            .thenReturn(ImmutableMap.of("ami_id", "bar"));
}
 
Example #19
Source File: FetchElasticLoadBalancersJob.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private void processELB(String account, Region awsRegion, LoadBalancerDescription elb) {
    final Map<String, Object> metaData = newHashMap();
    final List<String> errorMessages = newArrayList();
    final String canonicalHostedZoneName = elb.getCanonicalHostedZoneName();

    final List<String> instanceIds = elb.getInstances().stream().map(Instance::getInstanceId).collect(toList());

    instanceIds.stream()
            .map(id -> ec2Instance.getById(account, awsRegion, id))
            .filter(Optional::isPresent)
            .map(Optional::get)
            .map(com.amazonaws.services.ec2.model.Instance::getImageId)
            .map(amiId -> amiDetailsProvider.getAmiDetails(account, awsRegion, amiId))
            .findFirst()
            .ifPresent(metaData::putAll);

    if (violationService.violationExists(account, awsRegion.getName(), EVENT_ID, canonicalHostedZoneName, UNSECURED_PUBLIC_ENDPOINT)) {
        return;
    }

    final List<Integer> unsecuredPorts = portsChecker.check(elb);
    if (!unsecuredPorts.isEmpty()) {
        metaData.put("unsecuredPorts", unsecuredPorts);
        errorMessages.add(format("ELB %s listens on insecure ports! Only ports 80 and 443 are allowed",
                elb.getLoadBalancerName()));
    }


    final Map<String, SecurityGroupCheckDetails> unsecureGroups = securityGroupsChecker.check(
            elb.getSecurityGroups(),
            account,
            awsRegion);
    if (!unsecureGroups.isEmpty()) {
        metaData.put("unsecuredSecurityGroups", unsecureGroups);
        errorMessages.add("Unsecured security group! Only ports 80 and 443 are allowed");
    }


    if (errorMessages.size() > 0) {
        metaData.put("errorMessages", errorMessages);
        writeViolation(account, awsRegion.getName(), metaData, canonicalHostedZoneName, instanceIds);

        // skip http response check, as we are already having a violation here
        return;
    }


    // skip check for publicly available apps
    if (awsApplications.isPubliclyAccessible(account, awsRegion.getName(), instanceIds).orElse(false)) {
        return;
    }

    for (final Integer allowedPort : jobsProperties.getElbAllowedPorts()) {
        final HttpGetRootCall HttpGetRootCall = new HttpGetRootCall(httpclient, canonicalHostedZoneName, allowedPort);
        final ListenableFuture<HttpCallResult> listenableFuture = threadPoolTaskExecutor.submitListenable(HttpGetRootCall);
        listenableFuture.addCallback(
                httpCallResult -> {
                    log.debug("address: {} and port: {}", canonicalHostedZoneName, allowedPort);
                    if (httpCallResult.isOpen()) {
                        final Map<String, Object> md = ImmutableMap.<String, Object>builder()
                                .putAll(metaData)
                                .put("canonicalHostedZoneName", canonicalHostedZoneName)
                                .put("port", allowedPort)
                                .put("Error", httpCallResult.getMessage())
                                .build();
                        writeViolation(account, awsRegion.getName(), md, canonicalHostedZoneName, instanceIds);
                    }
                }, ex -> log.warn(ex.getMessage(), ex));

        log.debug("Active threads in pool: {}/{}", threadPoolTaskExecutor.getActiveCount(), threadPoolTaskExecutor.getMaxPoolSize());
    }
}
 
Example #20
Source File: LoadBalancerVH.java    From pacbot with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the instances.
 *
 * @param instances the new instances
 */
public void setInstances( List<Instance> instances){
	this.instances = instances;
}
 
Example #21
Source File: ElasticLoadBalancer.java    From Baragon with Apache License 2.0 votes vote down vote up
public abstract AgentCheckInResponse removeInstance(Instance instance, String id, String elbName, String agentId); 
Example #22
Source File: ElasticLoadBalancer.java    From Baragon with Apache License 2.0 votes vote down vote up
public abstract AgentCheckInResponse registerInstance(Instance instance, String id, String elbName, BaragonAgentMetadata agent); 
Example #23
Source File: ElasticLoadBalancer.java    From Baragon with Apache License 2.0 votes vote down vote up
public abstract AgentCheckInResponse checkRegisteredInstance(Instance instance, String id, TrafficSource trafficSource, BaragonAgentMetadata agent);