com.amazonaws.services.elasticloadbalancingv2.model.TargetDescription Java Examples

The following examples show how to use com.amazonaws.services.elasticloadbalancingv2.model.TargetDescription. 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: ELBRegisterInstanceStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected String run() throws Exception {
	TaskListener listener = this.getContext().get(TaskListener.class);
	listener.getLogger().println("elbRegisterInstance instanceID: " + this.step.instanceID + " port: " + this.step.port + " from targetGroupARN: " + this.step.targetGroupARN);
	ArrayList<TargetDescription> arr = new ArrayList<TargetDescription>();
	arr.add(new TargetDescription().withId(this.step.instanceID).withPort(this.step.port));
	RegisterTargetsRequest request = new RegisterTargetsRequest().withTargetGroupArn(this.step.targetGroupARN).withTargets( arr );
	AmazonElasticLoadBalancing client = AWSClientFactory.create(AmazonElasticLoadBalancingClientBuilder.standard(), this.getEnvVars());
	client.registerTargets(request);
	
	DescribeTargetHealthRequest req = new DescribeTargetHealthRequest().withTargetGroupArn(this.step.targetGroupARN);
	DescribeTargetHealthResult res = client.describeTargetHealth(req);
	listener.getLogger().println(res.toString());
	
	return null;
}
 
Example #2
Source File: ELBDeregisterInstanceStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected String run() throws Exception {
	TaskListener listener = this.getContext().get(TaskListener.class);
	listener.getLogger().println("elbDeregisterInstance instanceID: " + this.step.instanceID + " port: " + this.step.port + " from targetGroupARN: " + this.step.targetGroupARN);
	ArrayList<TargetDescription> arr = new ArrayList<TargetDescription>();
	arr.add(new TargetDescription().withId(this.step.instanceID).withPort(this.step.port));
	DeregisterTargetsRequest request = new DeregisterTargetsRequest().withTargetGroupArn(this.step.targetGroupARN).withTargets( arr );
	AmazonElasticLoadBalancing client = AWSClientFactory.create(AmazonElasticLoadBalancingClientBuilder.standard(), this.getEnvVars());
	client.deregisterTargets(request);
	
	DescribeTargetHealthRequest req = new DescribeTargetHealthRequest().withTargetGroupArn(this.step.targetGroupARN);
	DescribeTargetHealthResult res = client.describeTargetHealth(req);
	listener.getLogger().println(res.toString());
	
	return null;
}
 
Example #3
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 6 votes vote down vote up
private AgentCheckInResponse registerInstance(String id, TargetGroup targetGroup) {
  TargetDescription newTarget = new TargetDescription()
      .withId(id);

  if (!targetsOn(targetGroup).contains(newTarget.getId())) {
    try {
      RegisterTargetsRequest registerTargetsRequest = new RegisterTargetsRequest()
          .withTargets(newTarget)
          .withTargetGroupArn(targetGroup.getTargetGroupArn());
      elbClient.registerTargets(registerTargetsRequest);
      LOG.info("Registered instance {} with target group {}", newTarget.getId(), targetGroup);
    } catch (AmazonServiceException exn) {
      LOG.warn("Failed to register instance {} with target group {}", id, targetGroup);
      throw Throwables.propagate(exn);
    }

    return instanceHealthResponse(newTarget, targetGroup, id);
  } else {
    LOG.debug("Instance {} already registered with target group {}", id, targetGroup);
    return new AgentCheckInResponse(TrafficSourceState.DONE, Optional.absent(), 0L);
  }
}
 
Example #4
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure that the given baragon agent is attached to the given target group. When this function
 * completes, the baragon agent will be attached to the load balancer, whether or not it originally
 * was.
 *
 * @param baragonAgents BaragonAgent to register with given load balancer
 * @param loadBalancers Load balancer to register with
 */
private void guaranteeRegistered(TrafficSource trafficSource,
                                 TargetGroup targetGroup,
                                 Collection<TargetDescription> targets,
                                 Collection<BaragonAgentMetadata> baragonAgents,
                                 Collection<LoadBalancer> loadBalancers) {
  /*
  - Check that load balancers, baragon agents, target groups are on same VPC
  - Check that load balancers, targets are on same subnet (== AZ)
  - Check that all baragon agents are associated with a target on target group
  - Check that load balancers has listeners, rules to make talk to target group
   */

  if (configuration.isPresent() && configuration.get().isCheckForCorrectVpc()) {
    guaranteeSameVPC(targetGroup, baragonAgents, loadBalancers);
  }

  guaranteeAzEnabled(baragonAgents, loadBalancers);
  guaranteeHasAllTargets(trafficSource, targetGroup, targets, baragonAgents);
  //guaranteeListenersPresent(targetGroup, loadBalancers);
}
 
Example #5
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param target Target to check
 * @param targetGroup Group to check in
 * @return if the given target is the last healthy target in the given target group
 */
private boolean isLastHealthyInstance(TargetDescription target, TargetGroup targetGroup) {
  DescribeTargetHealthRequest targetHealthRequest = new DescribeTargetHealthRequest()
      .withTargetGroupArn(targetGroup.getTargetGroupArn());
  List<TargetHealthDescription> targetHealthDescriptions = elbClient
      .describeTargetHealth(targetHealthRequest)
      .getTargetHealthDescriptions();

  boolean instanceIsHealthy = false;
  int healthyCount = 0;

  for (TargetHealthDescription targetHealthDescription : targetHealthDescriptions) {
    if (targetHealthDescription.getTargetHealth().getState()
        .equals(TargetHealthStateEnum.Healthy.toString())) {
      healthyCount += 1;
      if (targetHealthDescription.getTarget().equals(target)) {
        instanceIsHealthy = true;
      }
    }
  }

  return instanceIsHealthy && healthyCount == 1;
}
 
Example #6
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 6 votes vote down vote up
private Collection<TargetDescription> listRemovableTargets(TrafficSource trafficSource,
                                                           BaragonGroup baragonGroup,
                                                           Collection<TargetDescription> targetsOnGroup,
                                                           Collection<BaragonAgentMetadata> agentsInBaragonGroup) {
  Collection<String> agentIds = trafficSource.getRegisterBy() == RegisterBy.INSTANCE_ID ? instanceIds(agentsInBaragonGroup) : privateIps(agentsInBaragonGroup);

  Collection<TargetDescription> removableTargets = new HashSet<>();
  for (TargetDescription targetDescription : targetsOnGroup) {
    if (!agentIds.contains(targetDescription.getId()) && canDeregisterAgent(baragonGroup, targetDescription.getId())) {
      LOG.info("Will attempt to deregister target {}", targetDescription.getId());
      removableTargets.add(targetDescription);
    }
  }

  return removableTargets;
}
 
Example #7
Source File: AwsLoadBalancerConnector.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public Completable registerAll(String loadBalancerId, Set<String> ipAddresses) {
    if (CollectionsExt.isNullOrEmpty(ipAddresses)) {
        return Completable.complete();
    }

    // TODO: retry logic
    // TODO: handle partial failures in the batch
    // TODO: timeouts

    final Set<TargetDescription> targetDescriptions = ipAddresses.stream().map(
            ipAddress -> new TargetDescription().withId(ipAddress)
    ).collect(Collectors.toSet());
    final RegisterTargetsRequest request = new RegisterTargetsRequest()
            .withTargetGroupArn(loadBalancerId)
            .withTargets(targetDescriptions);

    long startTime = registry.clock().wallTime();
    // force observeOn(scheduler) since the callback will be called from the AWS SDK threadpool
    return AwsObservableExt.asyncActionCompletable(factory -> getClient(loadBalancerId).registerTargetsAsync(request, factory.handler(
            (req, resp) -> {
                logger.debug("Registered targets {}", resp);
                connectorMetrics.success(AwsLoadBalancerConnectorMetrics.AwsLoadBalancerMethods.RegisterTargets, startTime);
            },
            (t) -> {
                logger.error("Error registering targets on " + loadBalancerId, t);
                connectorMetrics.failure(AwsLoadBalancerConnectorMetrics.AwsLoadBalancerMethods.RegisterTargets, t, startTime);
            }
    ))).observeOn(scheduler);
}
 
Example #8
Source File: AwsLoadBalancerConnector.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public Completable deregisterAll(String loadBalancerId, Set<String> ipAddresses) {
    if (CollectionsExt.isNullOrEmpty(ipAddresses)) {
        return Completable.complete();
    }

    // TODO: retry logic
    // TODO: handle partial failures in the batch
    // TODO: timeouts

    final DeregisterTargetsRequest request = new DeregisterTargetsRequest()
            .withTargetGroupArn(loadBalancerId)
            .withTargets(ipAddresses.stream().map(
                    ipAddress -> new TargetDescription().withId(ipAddress)
            ).collect(Collectors.toSet()));

    long startTime = registry.clock().wallTime();
    // force observeOn(scheduler) since the callback will be called from the AWS SDK threadpool
    return AwsObservableExt.asyncActionCompletable(supplier -> getClient(loadBalancerId).deregisterTargetsAsync(request, supplier.handler(
            (req, resp) -> {
                logger.debug("Deregistered targets {}", resp);
                connectorMetrics.success(AwsLoadBalancerConnectorMetrics.AwsLoadBalancerMethods.DeregisterTargets, startTime);
            },
            (t) -> {
                logger.error("Error deregistering targets on " + loadBalancerId, t);
                connectorMetrics.failure(AwsLoadBalancerConnectorMetrics.AwsLoadBalancerMethods.DeregisterTargets, t, startTime);
            }
    ))).observeOn(scheduler);
}
 
Example #9
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isInstanceHealthy(String instanceId, String elbName) {
  DescribeTargetHealthRequest healthRequest = new DescribeTargetHealthRequest()
      .withTargets(new TargetDescription().withId(instanceId));
  DescribeTargetHealthResult result = elbClient.describeTargetHealth(healthRequest);

  for (TargetHealthDescription health: result.getTargetHealthDescriptions()) {
    if (health.getTargetHealth().getState().equals(TargetHealthStateEnum.Healthy.toString())
        && health.getTarget().getId().equals(instanceId)) {
      return true;
    }
  }

  return false;
}
 
Example #10
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public AgentCheckInResponse removeInstance(String id, String trafficSourceName) {

    Optional<TargetGroup> maybeTargetGroup = getTargetGroup(trafficSourceName);
    if (maybeTargetGroup.isPresent()) {
      TargetGroup targetGroup = maybeTargetGroup.get();
      TargetDescription targetDescription = new TargetDescription()
          .withId(id);
      if (targetsOn(targetGroup).contains(targetDescription.getId())) {
        DeregisterTargetsRequest deregisterTargetsRequest = new DeregisterTargetsRequest()
            .withTargets(targetDescription)
            .withTargetGroupArn(targetGroup.getTargetGroupArn());
        try {
          elbClient.deregisterTargets(deregisterTargetsRequest);
          LOG.info("De-registered instance {} from target group {}", id, targetGroup);
          return getShutdownResponse(targetGroup.getTargetGroupArn(), targetDescription, true);
        } catch (AmazonServiceException exn) {
          LOG.warn("Failed to de-register instance {} from target group {}", id, targetGroup);
        }
      } else {
        LOG.debug("Instance {} not found at target group {}", id, targetGroup);
      }
    } else {
      LOG.debug("No target group found with name {}", trafficSourceName);
    }

    return new AgentCheckInResponse(TrafficSourceState.DONE, Optional.absent(), 0L);
  }
 
Example #11
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
public AgentCheckInResponse checkRemovedInstance(String id, String trafficSourceName, String agentId) {
  Optional<TargetGroup> maybeTargetGroup = getTargetGroup(trafficSourceName);
  if (maybeTargetGroup.isPresent()) {
    return getShutdownResponse(maybeTargetGroup.get().getTargetGroupArn(), new TargetDescription().withId(id), false);
  } else {
    String message = String.format("Could not find target group %s", trafficSourceName);
    LOG.error(message);
    return new AgentCheckInResponse(TrafficSourceState.ERROR, Optional.of(message), 0L);
  }
}
 
Example #12
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 #13
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
/**
 * De-register any targets representing agents that are not known to the BaragonService,
 * or which otherwise need to be removed.
 *
 * @param targetGroup TargetGroup to check for old agents
 * @param agents Known agents, to be used as a reference sheet
 */
private void deregisterRemovableTargets(TrafficSource trafficSource,
                                        BaragonGroup baragonGroup,
                                        TargetGroup targetGroup,
                                        Collection<BaragonAgentMetadata> agents,
                                        Collection<TargetDescription> targets) {
  Collection<TargetDescription> removableTargets = listRemovableTargets(trafficSource, baragonGroup, targets, agents);

  for (TargetDescription removableTarget : removableTargets) {
    try {
      if (configuration.isPresent()
          && !configuration.get().isRemoveLastHealthyEnabled()
          && isLastHealthyInstance(removableTarget, targetGroup)) {
        LOG.info("Will not de-register target {} because it is last healthy instance in {}", removableTarget, targetGroup);
      } else {
        elbClient.deregisterTargets(new DeregisterTargetsRequest()
            .withTargetGroupArn(targetGroup.getTargetGroupArn())
            .withTargets(removableTarget));
        LOG.info("De-registered target {} from target group {}", removableTarget, targetGroup);
      }
    } catch (AmazonClientException acexn) {
      LOG.error("Could not de-register target {} from target group {} due to error",
          removableTarget, targetGroup, acexn);
      exceptionNotifier.notify(acexn, ImmutableMap
          .of("targetGroup", targetGroup.getTargetGroupName()));
    }
  }
}
 
Example #14
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
private boolean agentShouldRegisterInTargetGroup(String id, Collection<TargetDescription> targets) {
  boolean shouldRegister = true;
  for (TargetDescription target : targets) {
    if (target.getId().equals(id)) {
      shouldRegister = false;
    }
  }
  return shouldRegister;
}
 
Example #15
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 5 votes vote down vote up
private Collection<TargetDescription> targetsInTargetGroup(TargetGroup targetGroup) {
  DescribeTargetHealthRequest targetHealthRequest = new DescribeTargetHealthRequest()
      .withTargetGroupArn(targetGroup.getTargetGroupArn());
  List<TargetHealthDescription> targetGroupsResult = elbClient
      .describeTargetHealth(targetHealthRequest)
      .getTargetHealthDescriptions();

  Collection<TargetDescription> targetDescriptions = new HashSet<>();
  for (TargetHealthDescription targetHealthDescription : targetGroupsResult) {
    targetDescriptions.add(targetHealthDescription.getTarget());
  }

  return targetDescriptions;
}
 
Example #16
Source File: ApplicationLoadBalancer.java    From Baragon with Apache License 2.0 4 votes vote down vote up
/**
 * After this method completes, every agent in baragonAgents should be associated with
 * a target in the given target group.
 *
 * @param targetGroup group to register in
 * @param baragonAgents agents to be registered
 */
private void guaranteeHasAllTargets(TrafficSource trafficSource,
                                    TargetGroup targetGroup,
                                    Collection<TargetDescription> targets,
                                    Collection<BaragonAgentMetadata> baragonAgents) {
  Collection<TargetDescription> targetDescriptions = new HashSet<>();
  for (BaragonAgentMetadata agent : baragonAgents) {
    try {
      if ((trafficSource.getRegisterBy() == RegisterBy.INSTANCE_ID && agent.getEc2().getInstanceId().isPresent())
          || (trafficSource.getRegisterBy() == RegisterBy.PRIVATE_IP && agent.getEc2().getPrivateIp().isPresent())) {
        String id = trafficSource.getRegisterBy() == RegisterBy.INSTANCE_ID ? agent.getEc2().getInstanceId().get() : agent.getEc2().getPrivateIp().get();
        if (agentShouldRegisterInTargetGroup(id, targets)) {
          targetDescriptions.add(new TargetDescription()
              .withId(id));
          LOG.info("Will register agent {} to target in group {}", agent, targetGroup);
        } else {
          LOG.debug("Agent {} is already registered", agent);
        }
      }
    } catch (Exception exn) {
      LOG.error("Could not create request to register agent {} due to error", agent, exn);
      exceptionNotifier.notify(exn, ImmutableMap.of("agent", agent.toString()));
    }
  }

  if (targetDescriptions.isEmpty()) {
    LOG.debug("No new instances to register with target group");
  } else {
    try {
      RegisterTargetsRequest registerTargetsRequest = new RegisterTargetsRequest()
          .withTargetGroupArn(targetGroup.getTargetGroupArn())
          .withTargets(targetDescriptions);
      elbClient.registerTargets(registerTargetsRequest);
      LOG.info("Registered targets {} onto target group {}", targetDescriptions, targetGroup);
    } catch (AmazonClientException acexn) {
      LOG.error("Failed to register targets {} onto target group {}", targetDescriptions, targetGroup);
      exceptionNotifier.notify(acexn, ImmutableMap.of(
          "targets", targetDescriptions.toString(),
          "targetGroup", targetGroup.toString()));
    }
  }
}