@Test
  public void testApply() {
    IpPermissions authorization = IpPermissions.permitAnyProtocol();

    org.jclouds.ec2.domain.SecurityGroup origGroup =
        org.jclouds.ec2.domain.SecurityGroup.builder()
            .region("us-east-1")
            .id("some-id")
            .name("some-group")
            .ownerId("some-owner")
            .description("some-description")
            .ipPermission(authorization)
            .build();

    AWSEC2SecurityGroupToSecurityGroup parser = createGroupParser(ImmutableSet.of(provider));

    SecurityGroup group = parser.apply(origGroup);

    assertEquals(group.getLocation(), provider);
    assertEquals(group.getId(), provider.getId() + "/" + origGroup.getId());
    assertEquals(group.getProviderId(), origGroup.getId());
    assertEquals(group.getName(), origGroup.getName());
    assertEquals(group.getIpPermissions(), (Set<IpPermission>) origGroup);
    assertEquals(group.getOwnerId(), origGroup.getOwnerId());
  }
  /**
   * Loads the security groups attached to the node with the given ID and returns the group that is
   * unique to the node, per the application context. This method will also update {@link
   * #sharedGroupCache} if no mapping for the shared group's location previously existed (e.g.
   * Brooklyn was restarted and rebound to an existing application).
   *
   * <p>Notice that jclouds will attach 2 securityGroups to the node if the locationId is `aws-ec2`
   * so it needs to look for the uniqueSecurityGroup rather than the shared securityGroup.
   *
   * @param nodeId The id of the node in question
   * @param locationId The id of the location in question
   * @param securityApi The API to use to list security groups
   * @return the security group unique to the given node, or null if one could not be determined.
   */
  private SecurityGroup getUniqueSecurityGroupForNodeCachingSharedGroupIfPreviouslyUnknown(
      String nodeId, String locationId, SecurityGroupExtension securityApi) {
    Set<SecurityGroup> groupsOnNode = securityApi.listSecurityGroupsForNode(nodeId);

    if (groupsOnNode == null || groupsOnNode.isEmpty()) {
      return null;
    }

    SecurityGroup unique;
    if (locationId.equals("aws-ec2")) {
      if (groupsOnNode.size() == 2) {
        String expectedSharedName = getNameForSharedSecurityGroup();
        Iterator<SecurityGroup> it = groupsOnNode.iterator();
        SecurityGroup shared = it.next();
        if (shared.getName().endsWith(expectedSharedName)) {
          unique = it.next();
        } else {
          unique = shared;
          shared = it.next();
        }
        if (!shared.getName().endsWith(expectedSharedName)) {
          LOG.warn(
              "Couldn't determine which security group is shared between instances in app {}. Expected={}, found={}",
              new Object[] {applicationId, expectedSharedName, groupsOnNode});
          return null;
        }
        // Shared entry might be missing if Brooklyn has rebound to an application
        SecurityGroup old = sharedGroupCache.asMap().putIfAbsent(shared.getLocation(), shared);
        LOG.info(
            "Loaded unique security group for node {} (in {}): {}",
            new Object[] {nodeId, applicationId, unique});
        if (old == null) {
          LOG.info("Proactively set shared group for app {} to: {}", applicationId, shared);
        }
        return unique;
      } else {
        LOG.warn(
            "Expected to find two security groups on node {} in app {} (one shared, one unique). Found {}: {}",
            new Object[] {nodeId, applicationId, groupsOnNode.size(), groupsOnNode});
      }
    }
    return Iterables.getOnlyElement(groupsOnNode);
  }
 protected SecurityGroup removePermission(
     final IpPermission permission,
     final SecurityGroup group,
     final SecurityGroupExtension securityApi) {
   LOG.debug("Removing permission from security group {}: {}", group.getName(), permission);
   Callable<SecurityGroup> callable =
       new Callable<SecurityGroup>() {
         @Override
         public SecurityGroup call() throws Exception {
           return securityApi.removeIpPermission(permission, group);
         }
       };
   return runOperationWithRetry(callable);
 }
 protected SecurityGroup addPermission(
     final IpPermission permission,
     final SecurityGroup group,
     final SecurityGroupExtension securityApi) {
   LOG.debug("Adding permission to security group {}: {}", group.getName(), permission);
   Callable<SecurityGroup> callable =
       new Callable<SecurityGroup>() {
         @Override
         public SecurityGroup call() throws Exception {
           try {
             return securityApi.addIpPermission(permission, group);
           } catch (AWSResponseException e) {
             if ("InvalidPermission.Duplicate".equals(e.getError().getCode())) {
               // already exists
               LOG.info(
                   "Permission already exists for security group; continuing (logging underlying exception at debug): permission="
                       + permission
                       + "; group="
                       + group);
               LOG.debug(
                   "Permission already exists for security group; continuing: permission="
                       + permission
                       + "; group="
                       + group,
                   e);
               return null;
             } else {
               throw e;
             }
           } catch (Exception e) {
             Exceptions.propagateIfFatal(e);
             if (e.toString().contains("InvalidPermission.Duplicate")) {
               // belt-and-braces, in case
               // already exists
               LOG.info(
                   "Permission already exists for security group; continuing (but unexpected exception type): permission="
                       + permission
                       + "; group="
                       + group,
                   e);
               return null;
             } else {
               throw Exceptions.propagate(e);
             }
           }
         }
       };
   return runOperationWithRetry(callable);
 }
  @Test
  public void testApplyWithGroup() {
    NovaSecurityGroupInZoneToSecurityGroup parser = createGroupParser();

    SecurityGroupInZone origGroup = new SecurityGroupInZone(securityGroupWithGroup(), zone.getId());

    SecurityGroup newGroup = parser.apply(origGroup);

    assertEquals(
        newGroup.getId(), origGroup.getZone() + "/" + origGroup.getSecurityGroup().getId());
    assertEquals(newGroup.getProviderId(), origGroup.getSecurityGroup().getId());
    assertEquals(newGroup.getName(), origGroup.getSecurityGroup().getName());
    assertEquals(newGroup.getOwnerId(), origGroup.getSecurityGroup().getTenantId());
    assertEquals(
        newGroup.getIpPermissions(),
        ImmutableSet.copyOf(
            transform(
                origGroup.getSecurityGroup().getRules(),
                NovaSecurityGroupToSecurityGroupTest.ruleConverter)));
    assertEquals(newGroup.getLocation().getId(), origGroup.getZone());
  }
  private void setSecurityGroupOnTemplate(
      final JcloudsLocation location,
      final Template template,
      final SecurityGroupExtension securityApi) {
    SecurityGroup shared;
    Tasks.setBlockingDetails(
        "Loading security group shared by instances in "
            + template.getLocation()
            + " in app "
            + applicationId);
    try {
      shared =
          sharedGroupCache.get(
              template.getLocation(),
              new Callable<SecurityGroup>() {
                @Override
                public SecurityGroup call() throws Exception {
                  return getOrCreateSharedSecurityGroup(template.getLocation(), securityApi);
                }
              });
    } catch (ExecutionException e) {
      throw Throwables.propagate(new Exception(e.getCause()));
    } finally {
      Tasks.resetBlockingDetails();
    }

    Set<String> originalGroups = template.getOptions().getGroups();
    template.getOptions().securityGroups(shared.getName());
    if (!originalGroups.isEmpty()) {
      LOG.info(
          "Replaced configured security groups: configured={}, replaced with={}",
          originalGroups,
          template.getOptions().getGroups());
    } else {
      LOG.debug(
          "Configured security groups at {} to: {}", location, template.getOptions().getGroups());
    }
  }