Java 类com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest 实例源码

项目:photon-model    文件:AWSSecurityGroupClient.java   
public DeferredResult<DescribeSecurityGroupsResult> getSecurityGroups(List<String> secGroupIds,
        String vpcId, String nicName, String vmName) {
    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest()
            .withFilters(new Filter(AWS_GROUP_ID_FILTER, secGroupIds))
            .withFilters(new Filter(AWS_VPC_ID_FILTER, singletonList(vpcId)));

    String msg = "Getting AWS Security Groups by id ["
            + secGroupIds
            + "] for [" + nicName + "] NIC for ["
            + vmName
            + "] VM";

    AWSDeferredResultAsyncHandler<DescribeSecurityGroupsRequest, DescribeSecurityGroupsResult>
            handler = new AWSDeferredResultAsyncHandler<>(this.service, msg);

    this.client.describeSecurityGroupsAsync(req, handler);

    return handler.toDeferredResult();

}
项目:photon-model    文件:AWSSecurityGroupEnumerationAdapterService.java   
@Override
protected DeferredResult<RemoteResourcesPage> getExternalResources(
        String nextPageLink) {
    this.service.logFine(() -> "Getting SecurityGroups from AWS");
    DescribeSecurityGroupsRequest securityGroupsRequest = new DescribeSecurityGroupsRequest();

    String msg = "Getting AWS Security Groups [" + this.request.original.resourceReference
            + "]";

    AWSDeferredResultAsyncHandler<DescribeSecurityGroupsRequest, DescribeSecurityGroupsResult> asyncHandler =
            new AWSDeferredResultAsyncHandler<>(this.service, msg);
    this.amazonEC2Client.describeSecurityGroupsAsync(securityGroupsRequest, asyncHandler);

    return asyncHandler.toDeferredResult().thenCompose((securityGroupsResult) -> {

        RemoteResourcesPage page = new RemoteResourcesPage();

        for (SecurityGroup securityGroup : securityGroupsResult.getSecurityGroups()) {

            page.resourcesPage.put(securityGroup.getGroupId(), securityGroup);
        }

        return DeferredResult.completed(page);
    });
}
项目:director-aws-plugin    文件:EC2NetworkValidator.java   
/**
 * Validates the actual security group permissions against the pre-defined network rules.
 *
 * @param client              the EC2 client
 * @param configuration       the configuration to be validated
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 */
private void checkSecurityGroups(AmazonEC2Client client,
                                 Configured configuration,
                                 PluginExceptionConditionAccumulator accumulator,
                                 LocalizationContext localizationContext) {
  List<String> securityGroupIds = EC2InstanceTemplate.CSV_SPLITTER.splitToList(
      configuration.getConfigurationValue(SECURITY_GROUP_IDS, localizationContext));
  List<SecurityGroup> securityGroups = Collections.emptyList();
  try {
    DescribeSecurityGroupsResult result = client.describeSecurityGroups(
        new DescribeSecurityGroupsRequest().withGroupIds(securityGroupIds));
    securityGroups = result.getSecurityGroups();
  } catch (AmazonServiceException e) {
    if (!e.getErrorCode().startsWith(INVALID_SECURITY_GROUP)) {
      throw Throwables.propagate(e);
    }
    // Otherwise, the error should be caught in anther validation,
    // EC2InstanceTemplateConfigurationValidator.checkSecurityGroupIds()
  }

  for (Direction direction : Direction.values()) {
    checkRulesForSecurityGroups(securityGroups, direction, accumulator,
        localizationContext);
  }
}
项目:cloud-runner    文件:AmazonEC2.java   
public static String getSecurityGroupId() {
    connect();

    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest();

    ArrayList<String> groupNames = new ArrayList<String>();
    groupNames.add(Configuration.SECURITY_GROUP_NAME);
    req.setGroupNames(groupNames);

    DescribeSecurityGroupsResult res = client.describeSecurityGroups(req);
    List<SecurityGroup> securityGroups = res.getSecurityGroups();

    if (securityGroups == null || securityGroups.size() == 0)
        return null;

    return securityGroups.get(0).getGroupId();
}
项目:fullstop    文件:SecurityGroupsCheckerImpl.java   
@Override
public Map<String, SecurityGroupCheckDetails> check(final Collection<String> groupIds, final String account, final Region region) {
    final DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    describeSecurityGroupsRequest.setGroupIds(groupIds);
    final AmazonEC2Client amazonEC2Client = clientProvider.getClient(
            AmazonEC2Client.class,
            account, region);
    final DescribeSecurityGroupsResult describeSecurityGroupsResult = amazonEC2Client.describeSecurityGroups(
            describeSecurityGroupsRequest);


    final ImmutableMap.Builder<String, SecurityGroupCheckDetails> result = ImmutableMap.builder();

    for (final SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) {
        final List<String> offendingRules = securityGroup.getIpPermissions().stream()
                .filter(isOffending)
                .map(Object::toString)
                .collect(toList());
        if (!offendingRules.isEmpty()) {
            final SecurityGroupCheckDetails details = new SecurityGroupCheckDetails(
                    securityGroup.getGroupName(), ImmutableList.copyOf(offendingRules));
            result.put(securityGroup.getGroupId(), details);
        }
    }
    return result.build();
}
项目:fullstop    文件:SecurityGroupProviderTest.java   
@Test
public void testAmazonException(){
    final AmazonServiceException amazonServiceException = new AmazonServiceException("");
    amazonServiceException.setErrorCode("InvalidGroup.NotFound");

    when(clientProviderMock.getClient(any(), anyString(), any(Region.class))).thenReturn(amazonEC2ClientMock);
    when(amazonEC2ClientMock.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class))).thenThrow(amazonServiceException);

    securityGroupProvider = new SecurityGroupProvider(clientProviderMock);
    final String securityGroup = securityGroupProvider.getSecurityGroup(Lists.newArrayList("sg.1234"), REGION, "9876");

    Assertions.assertThat(securityGroup).isEqualTo(null);

    verify(clientProviderMock).getClient(any(), anyString(), any(Region.class));
    verify(amazonEC2ClientMock).describeSecurityGroups(any(DescribeSecurityGroupsRequest.class));
}
项目:fullstop    文件:SecurityGroupProviderTest.java   
@Test
public void testJsonException(){
    final DescribeSecurityGroupsResult mockResult = spy(new DescribeSecurityGroupsResult());

    when(clientProviderMock.getClient(any(), anyString(), any(Region.class))).thenReturn(amazonEC2ClientMock);
    when(mockResult.getSecurityGroups()).thenThrow(new IllegalStateException());
    when(amazonEC2ClientMock.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class))).thenReturn(mockResult);

    securityGroupProvider = new SecurityGroupProvider(clientProviderMock);
    final String securityGroup = securityGroupProvider.getSecurityGroup(Lists.newArrayList("sg.1234"), REGION, "9876");

    Assertions.assertThat(securityGroup).isEqualTo(null);

    verify(clientProviderMock).getClient(any(), anyString(), any(Region.class));
    verify(amazonEC2ClientMock).describeSecurityGroups(any(DescribeSecurityGroupsRequest.class));
}
项目:primecloud-controller    文件:AwsDescribeServiceImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public List<SecurityGroup> getSecurityGroups(Long userNo, Long platformNo) {
    // セキュリティグループを取得
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo);
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    PlatformAws platformAws = platformAwsDao.read(platformNo);
    if (BooleanUtils.isTrue(platformAws.getVpc())) {
        // VPCの場合、VPC IDが同じものを抽出
        request.withFilters(new Filter().withName("vpc-id").withValues(platformAws.getVpcId()));
    } else {
        // 非VPCの場合、VPC IDが空のものを抽出
        request.withFilters(new Filter().withName("vpc-id").withValues(""));
    }
    DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request);
    List<SecurityGroup> securityGroups = result.getSecurityGroups();

    // ソート
    Collections.sort(securityGroups, Comparators.COMPARATOR_SECURITY_GROUP);

    return securityGroups;
}
项目:incubator-provisionr    文件:DeleteSecurityGroupLiveTest.java   
@Test
public void testDeleteSecurityGroup() throws Exception {
    DelegateExecution execution = mock(DelegateExecution.class);
    Pool pool = mock(Pool.class);

    when(pool.getProvider()).thenReturn(provider);
    when(execution.getVariable(CoreProcessVariables.POOL)).thenReturn(pool);
    when(execution.getProcessBusinessKey()).thenReturn(BUSINESS_KEY);

    client.createSecurityGroup(new CreateSecurityGroupRequest()
        .withGroupName(SECURITY_GROUP_NAME).withDescription("Just for test"));

    activity.execute(execution);

    try {
        client.describeSecurityGroups(new DescribeSecurityGroupsRequest()
            .withGroupNames(SECURITY_GROUP_NAME));
        fail("Did not throw AmazonServiceException as expected");

    } catch (AmazonServiceException e) {
        assertThat(e.getErrorCode()).isEqualTo("InvalidGroup.NotFound");
    }
}
项目:usergrid    文件:AmazonIpRuleManager.java   
@Override
public Collection<String> listRuleSets() {
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    DescribeSecurityGroupsResult result = null;
    try {
        result = client.describeSecurityGroups( request );
    }
    catch ( Exception e ) {
        LOG.warn( "Error while getting security groups", e );
        return new LinkedList<String>();
    }
    Collection<String> groups = new ArrayList<String>();
    for( SecurityGroup group : result.getSecurityGroups() ) {
        groups.add( group.getGroupName() );
    }
    return groups;
}
项目:usergrid    文件:AmazonIpRuleManager.java   
@Override
public Collection<IpRule> getRules( final String name, final boolean inbound ) {
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupNames( name );
    DescribeSecurityGroupsResult result = client.describeSecurityGroups( request );

    if( result.getSecurityGroups().size() != 1 ) {
        return null;
    }

    Collection<IpRule> ipRules = new ArrayList<IpRule>();
    List<IpPermission> permissions;

    if( inbound ) {
        permissions = result.getSecurityGroups().get( 0 ).getIpPermissions();
    }
    else {
        permissions = result.getSecurityGroups().get( 0 ).getIpPermissionsEgress();
    }

    for( IpPermission permission : permissions ) {
        ipRules.add( toIpRule( permission ) );
    }

    return ipRules;
}
项目:photon-model    文件:AWSSecurityGroupClient.java   
public SecurityGroup getSecurityGroupById(String groupId) {
    SecurityGroup cellGroup = null;

    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest()
            .withGroupIds(groupId);
    DescribeSecurityGroupsResult cellGroups = this.client.describeSecurityGroups(req);
    if (cellGroups != null) {
        cellGroup = cellGroups.getSecurityGroups().get(0);
    }
    return cellGroup;
}
项目:photon-model    文件:AWSSecurityGroupClient.java   
public List<SecurityGroup> getSecurityGroups(List<String> names, String vpcId) {

        DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest();

        req.withFilters(new Filter(AWS_GROUP_NAME_FILTER, names));
        if (vpcId != null) {
            req.withFilters(new Filter(AWS_VPC_ID_FILTER, Collections.singletonList(vpcId)));
        }

        DescribeSecurityGroupsResult groups = this.client.describeSecurityGroups(req);
        return groups != null ? groups.getSecurityGroups() : Collections.emptyList();
    }
项目:photon-model    文件:AWSSecurityGroupClient.java   
public SecurityGroup getSecurityGroup(String name, String vpcId) {
    SecurityGroup cellGroup = null;

    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest()
            .withFilters(new Filter("group-name", Collections.singletonList(name)));
    if (vpcId != null) {
        req.withFilters(new Filter("vpc-id", Collections.singletonList(vpcId)));
    }
    DescribeSecurityGroupsResult cellGroups = this.client.describeSecurityGroups(req);
    if (cellGroups != null && !cellGroups.getSecurityGroups().isEmpty()) {
        cellGroup = cellGroups.getSecurityGroups().get(0);
    }
    return cellGroup;
}
项目:photon-model    文件:AWSSecurityGroupClient.java   
public SecurityGroup getDefaultSecurityGroup(String vpcId) {
    SecurityGroup cellGroup = null;

    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest()
            .withFilters(new Filter("group-name",
                    Collections.singletonList(DEFAULT_SECURITY_GROUP_NAME)));
    if (vpcId != null) {
        req.withFilters(new Filter("vpc-id", Collections.singletonList(vpcId)));
    }
    DescribeSecurityGroupsResult cellGroups = this.client.describeSecurityGroups(req);
    if (cellGroups != null && !cellGroups.getSecurityGroups().isEmpty()) {
        cellGroup = cellGroups.getSecurityGroups().get(0);
    }
    return cellGroup;
}
项目:photon-model    文件:TestAWSSetupUtils.java   
public static SecurityGroup getSecurityGroupsIdUsingEC2Client(AmazonEC2AsyncClient client, String awsGroupId) {
    if (awsGroupId == null) {
        return null;
    }

    DescribeSecurityGroupsRequest describeSGsRequest = new DescribeSecurityGroupsRequest()
            .withFilters(new Filter(AWSConstants.AWS_GROUP_ID_FILTER,Collections.singletonList(awsGroupId)));
    DescribeSecurityGroupsResult describeSGResult = client.describeSecurityGroups(describeSGsRequest);

    if (describeSGResult.getSecurityGroups().size() > 0) {
        return describeSGResult.getSecurityGroups().get(0);
    } else {
        return null;
    }
}
项目:aws-doc-sdk-examples    文件:DescribeSecurityGroups.java   
public static void main(String[] args)
{
    final String USAGE =
        "To run this example, supply a group id\n" +
        "Ex: DescribeSecurityGroups <group-id>\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String group_id = args[0];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    DescribeSecurityGroupsRequest request =
        new DescribeSecurityGroupsRequest()
            .withGroupIds(group_id);

    DescribeSecurityGroupsResult response =
        ec2.describeSecurityGroups(request);

    for(SecurityGroup group : response.getSecurityGroups()) {
        System.out.printf(
            "Found security group with id %s, " +
            "vpc id %s " +
            "and description %s",
            group.getGroupId(),
            group.getVpcId(),
            group.getDescription());
    }
}
项目:cerberus-lifecycle-cli    文件:WhitelistCidrForVpcAccessOpertaion.java   
@Override
public void run(final WhitelistCidrForVpcAccessCommand command) {
    final BaseOutputs baseStackOutputs = configStore.getBaseStackOutputs();

    logger.info("Revoking the previous ingress rules...");
    final DescribeSecurityGroupsResult securityGroupsResult = ec2Client.describeSecurityGroups(
            new DescribeSecurityGroupsRequest().withGroupIds(baseStackOutputs.getToolsIngressSgId()));
    securityGroupsResult.getSecurityGroups().forEach(securityGroup -> {
        if (!securityGroup.getIpPermissions().isEmpty()) {
            RevokeSecurityGroupIngressRequest revokeIngressRequest = new RevokeSecurityGroupIngressRequest()
                    .withGroupId(baseStackOutputs.getToolsIngressSgId())
                    .withIpPermissions(securityGroup.getIpPermissions());
            ec2Client.revokeSecurityGroupIngress(revokeIngressRequest);
        }
    });
    logger.info("Done.");

    logger.info("Authorizing the new ingress rules...");
    final List<IpPermission> ipPermissionList = Lists.newArrayListWithCapacity(command.getPorts().size());
    command.getPorts().forEach(port -> {
        IpPermission ipPermission = new IpPermission()
                .withIpRanges(command.getCidrs())
                .withIpProtocol("tcp")
                .withFromPort(port)
                .withToPort(port);

        ipPermissionList.add(ipPermission);
    });

    AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest()
            .withGroupId(baseStackOutputs.getToolsIngressSgId())
            .withIpPermissions(ipPermissionList);
    ec2Client.authorizeSecurityGroupIngress(ingressRequest);
    logger.info("Done.");
}
项目:director-aws-plugin    文件:EC2InstanceTemplateConfigurationValidator.java   
/**
 * Validates the configured security group IDs.
 *
 * @param client              the EC2 client
 * @param configuration       the configuration to be validated
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 *
 * @return the vpc id to security group ids mapping
 */
@VisibleForTesting
Map<String, Set<String>> checkSecurityGroupIds(AmazonEC2Client client,
    Configured configuration,
    PluginExceptionConditionAccumulator accumulator,
    LocalizationContext localizationContext) {

  List<String> securityGroupsIds = EC2InstanceTemplate.CSV_SPLITTER.splitToList(
      configuration.getConfigurationValue(SECURITY_GROUP_IDS, localizationContext));

  Map<String, Set<String>> vpcSgMap = Maps.newHashMap();
  for (String securityGroupId : securityGroupsIds) {
    LOG.info(">> Describing security group '{}'", securityGroupId);

    try {
      DescribeSecurityGroupsResult result = client.describeSecurityGroups(
          new DescribeSecurityGroupsRequest().withGroupIds(securityGroupId));
      checkCount(accumulator, SECURITY_GROUP_IDS, localizationContext, securityGroupId,
          result.getSecurityGroups()
      );
      if (result.getSecurityGroups().size() == 1) {
        String vpcId = Iterables.getOnlyElement(result.getSecurityGroups()).getVpcId();
        Set<String> sgSet = vpcSgMap.get(vpcId);
        if (sgSet == null) {
          sgSet = Sets.newHashSet();
          vpcSgMap.put(vpcId, sgSet);
        }
        sgSet.add(securityGroupId);
      }
    } catch (AmazonServiceException e) {
      if (e.getErrorCode().startsWith(INVALID_SECURITY_GROUP)) {
        addError(accumulator, SECURITY_GROUP_IDS, localizationContext,
            null, INVALID_SECURITY_GROUP_MSG, securityGroupId);
      } else {
        throw Throwables.propagate(e);
      }
    }
  }
  return vpcSgMap;
}
项目:cmn-project    文件:SGLoader.java   
private void loadSecurityGroups(Map<String, SecurityGroup> securityGroups) {
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest()
        .withGroupIds(securityGroups.keySet());

    for (com.amazonaws.services.ec2.model.SecurityGroup remoteSecurityGroup : AWS.ec2.ec2.describeSecurityGroups(request).getSecurityGroups()) {
        SecurityGroup securityGroup = securityGroups.get(remoteSecurityGroup.getGroupId());
        securityGroup.name = remoteSecurityGroup.getGroupName();
        securityGroup.remoteSecurityGroup = remoteSecurityGroup;
    }
}
项目:dohko    文件:EC2.java   
public void createSecurityGroupIfDoesNotExist(String groupName)
{
    checkState(!isNullOrEmpty(groupName));

    List<SecurityGroup> groups = newArrayList();

    try
    {
        LOG.debug("checking if the security group [{}] already exists on region [{}].", groupName, DEFAULT_API_REGION.getName());
        groups = ec2_.describeSecurityGroups(new DescribeSecurityGroupsRequest().withGroupNames(groupName)).getSecurityGroups();
    }
    catch (AmazonServiceException exception)
    {
        LOG.debug("The security group {} does not already exist on region {}.", groupName, DEFAULT_API_REGION.getName());
    }

    if (groups.isEmpty())
    {
        LOG.debug("Creating the security group [{}] on region [{}].", groupName, DEFAULT_API_REGION.getName());

        CreateSecurityGroupResult createSecurityGroup = ec2_.createSecurityGroup(new CreateSecurityGroupRequest()
                .withGroupName(groupName)
                .withDescription("default-app-group"));

        LOG.debug("The security group [{}] was created on region [{}], and its id is [{}]", groupName, 
                DEFAULT_API_REGION.getName(), 
                createSecurityGroup.getGroupId());

        authorizeTcpAndSshIngressTraffic(groupName);
    }
}
项目:primecloud-controller    文件:AwsCommonProcess.java   
public List<SecurityGroup> describeSecurityGroupsByVpcId(AwsProcessClient awsProcessClient, String vpcId) {
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    request.withFilters(new Filter().withName("vpc-id").withValues(vpcId));
    DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request);
    List<SecurityGroup> securityGroups = result.getSecurityGroups();

    return securityGroups;
}
项目:aws-sdk-java-resources    文件:VpcImpl.java   
@Override
public SecurityGroupCollection getSecurityGroups(
        DescribeSecurityGroupsRequest request) {

    ResourceCollectionImpl result = resource.getCollection("SecurityGroups",
            request);

    if (result == null) return null;
    return new SecurityGroupCollectionImpl(result);
}
项目:aws-sdk-java-resources    文件:EC2Impl.java   
@Override
public SecurityGroupCollection getSecurityGroups(
        DescribeSecurityGroupsRequest request) {

    ResourceCollectionImpl result = service.getCollection("SecurityGroups",
            request);

    if (result == null) return null;
    return new SecurityGroupCollectionImpl(result);
}
项目:cloudbreak    文件:AwsPlatformResources.java   
@Override
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    Map<String, Set<CloudSecurityGroup>> result = new HashMap<>();
    Set<CloudSecurityGroup> cloudSecurityGroups = new HashSet<>();
    AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), region.value());

    //create securitygroup filter view
    PlatformResourceSecurityGroupFilterView filter = new PlatformResourceSecurityGroupFilterView(filters);

    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    // If the filtervalue is provided then we should filter only for those securitygroups
    if (!Strings.isNullOrEmpty(filter.getVpcId())) {
        describeSecurityGroupsRequest.withFilters(new Filter("vpc-id", singletonList(filter.getVpcId())));
    }
    if (!Strings.isNullOrEmpty(filter.getGroupId())) {
        describeSecurityGroupsRequest.withGroupIds(filter.getGroupId());
    }
    if (!Strings.isNullOrEmpty(filter.getGroupName())) {
        describeSecurityGroupsRequest.withGroupNames(filter.getGroupName());
    }

    for (SecurityGroup securityGroup : ec2Client.describeSecurityGroups(describeSecurityGroupsRequest).getSecurityGroups()) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("vpcId", securityGroup.getVpcId());
        properties.put("description", securityGroup.getDescription());
        properties.put("ipPermissions", securityGroup.getIpPermissions());
        properties.put("ipPermissionsEgress", securityGroup.getIpPermissionsEgress());
        cloudSecurityGroups.add(new CloudSecurityGroup(securityGroup.getGroupName(), securityGroup.getGroupId(), properties));
    }
    result.put(region.value(), cloudSecurityGroups);
    return new CloudSecurityGroups(result);
}
项目:clouck    文件:Ec2WrapperImpl.java   
@Override
public List<AbstractResource<?>> describeSecurityGroups(Account account, Region region, DateTime dt, Ec2Filter... filters) {
    AmazonEC2 ec2 = findClient(account, region);

    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest();
    for (Ec2Filter filter : filters) {
        Filter f = new Filter().withName(filter.getName()).withValues(filter.getValues());
        req.withFilters(f);
    }
    log.debug("start describing security groups for account:{} in region:{} via api", account.getId() + "=>" + account.getName(), region);
    DescribeSecurityGroupsResult res = ec2.describeSecurityGroups(req);

    return converter.toEc2SecurityGroups(res.getSecurityGroups(), account.getId(), region, dt);
}
项目:incubator-provisionr    文件:EnsureSecurityGroupExists.java   
private void synchronizeIngressRules(AmazonEC2 client, String groupName, Network network) {
    DescribeSecurityGroupsResult result = client.describeSecurityGroups(
        new DescribeSecurityGroupsRequest().withGroupNames(groupName));

    Set<IpPermission> existingPermissions = ImmutableSet.copyOf(getOnlyElement(
        result.getSecurityGroups()).getIpPermissions());

    Set<IpPermission> expectedPermissions = ImmutableSet.copyOf(
        Iterables.transform(network.getIngress(), ConvertRuleToIpPermission.FUNCTION));

    authorizeIngressRules(client, groupName, difference(expectedPermissions, existingPermissions));
    revokeIngressRules(client, groupName, difference(existingPermissions, expectedPermissions));
}
项目:incubator-provisionr    文件:EnsureSecurityGroupExistsLiveTest.java   
public void assertSecurityGroupExistsWithRules(String groupName, final Set<Rule> ingressRules) {
    DescribeSecurityGroupsResult result = client.describeSecurityGroups(
        new DescribeSecurityGroupsRequest().withGroupNames(groupName));

    assertThat(result.getSecurityGroups()).hasSize(1);
    SecurityGroup group = getOnlyElement(result.getSecurityGroups());

    assertThat(group.getIpPermissions()).hasSize(ingressRules.size());
    assertThat(ingressRules).containsAll(transform(group.getIpPermissions(),
        ConvertIpPermissionToRule.FUNCTION));
}
项目:cfnassist    文件:TestManageSecGroups.java   
private static void deleteGroupIfPresent() {
    try {   
        DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest().withGroupNames(GROUP_NAME);
        DescribeSecurityGroupsResult existing = ec2Client.describeSecurityGroups(describeSecurityGroupsRequest);
        if (existing.getSecurityGroups().size()>0) {
            DeleteSecurityGroupRequest deleteGroup = new DeleteSecurityGroupRequest().withGroupName(GROUP_NAME);
            ec2Client.deleteSecurityGroup(deleteGroup); 
        }
    } catch (AmazonServiceException exception) {
        // no op
    }
}
项目:cfnassist    文件:TestManageSecGroups.java   
@Test
public void testShouldAddAndDeleteAnIpToASecurityGroup() throws UnknownHostException {
    Integer port = 8080;
    InetAddress adddress = Inet4Address.getByName("192.168.0.1");
    String cidr = "192.168.0.1/32";

    //add
    client.addIpToSecGroup(groupId, port , adddress);

    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupIds(groupId);
    DescribeSecurityGroupsResult result = ec2Client.describeSecurityGroups(request);

    List<SecurityGroup> securityGroups = result.getSecurityGroups();
    assertEquals(1, securityGroups.size());
    SecurityGroup group = securityGroups.get(0);

    List<IpPermission> perms = group.getIpPermissions();
    assertEquals(1, perms.size());

    IpPermission ipPermission = perms.get(0);
    assertEquals(port, ipPermission.getToPort());
    assertEquals(port, ipPermission.getFromPort());
    assertEquals(1, ipPermission.getIpv4Ranges().size());
    assertEquals(cidr, ipPermission.getIpv4Ranges().get(0).getCidrIp());

    //remove
    client.deleteIpFromSecGroup(groupId, port, adddress);

    result = ec2Client.describeSecurityGroups(request);
    securityGroups = result.getSecurityGroups();
    assertEquals(1, securityGroups.size());
    group = securityGroups.get(0);
    perms = group.getIpPermissions();
    assertEquals(0, perms.size());
}
项目:aws-mock    文件:BaseTest.java   
/**
 * Describe security group.
 *
 * @return SecurityGroup
 */
protected final SecurityGroup getSecurityGroup() {
    SecurityGroup cellGroup = null;

    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest();
    DescribeSecurityGroupsResult result = amazonEC2Client.describeSecurityGroups(req);
    if (result != null && !result.getSecurityGroups().isEmpty()) {
        cellGroup = result.getSecurityGroups().get(0);
    }

    return cellGroup;
}
项目:elasticsearch_my    文件:AmazonEC2Mock.java   
@Override
public DescribeSecurityGroupsResult describeSecurityGroups(DescribeSecurityGroupsRequest describeSecurityGroupsRequest) throws AmazonServiceException, AmazonClientException {
    throw new UnsupportedOperationException("Not supported in mock");
}
项目:Raigad    文件:SetVPCSecurityGroupID.java   
public void execute() {
    AmazonEC2 client = null;

    try {
        client = getEc2Client();

        //Get All the Existing Sec Group Ids
        String[] securityGroupIds = SystemUtils.getSecurityGroupIds(config.getMacIdForInstance());
        DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest().withGroupIds(securityGroupIds);
        DescribeSecurityGroupsResult result = client.describeSecurityGroups(req);

        boolean securityGroupFound = false;

        for (SecurityGroup securityGroup : result.getSecurityGroups()) {
            logger.info("Read " + securityGroup.getGroupName());

            if (securityGroup.getGroupName().equals(config.getACLGroupNameForVPC())) {
                logger.info("Found matching security group name: " + securityGroup.getGroupName());

                // Setting configuration value with the correct SG ID
                config.setACLGroupIdForVPC(securityGroup.getGroupId());
                securityGroupFound = true;

                break;
            }
        }

        // If correct SG was not found, throw Exception
        if (!securityGroupFound) {
            throw new RuntimeException("Cannot find matching security group for " + config.getACLGroupNameForVPC());
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
    finally {
        if (client != null) {
            client.shutdown();
        }
    }
}
项目:aws-sdk-java-resources    文件:SecurityGroupImpl.java   
@Override
public boolean load(DescribeSecurityGroupsRequest request) {
    return load(request, null);
}
项目:aws-sdk-java-resources    文件:SecurityGroupImpl.java   
@Override
public boolean load(DescribeSecurityGroupsRequest request,
        ResultCapture<DescribeSecurityGroupsResult> extractor) {

    return resource.load(request, extractor);
}
项目:aws-sdk-java-resources    文件:EC2Impl.java   
@Override
public SecurityGroupCollection getSecurityGroups() {
    return getSecurityGroups((DescribeSecurityGroupsRequest)null);
}
项目:aws-connector-extension    文件:AWSConnector.java   
private void validateAndConfigureSecurityGroups(List<String> securityGroupNamesOrIds, AmazonEC2 connector, boolean withNames) throws ConnectorException {
    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    if (withNames) {
        describeSecurityGroupsRequest.withGroupNames(securityGroupNamesOrIds);
    } else {
        describeSecurityGroupsRequest.withGroupIds(securityGroupNamesOrIds);
    }

    DescribeSecurityGroupsResult describeSecurityGroupsResult = connector.describeSecurityGroups(describeSecurityGroupsRequest);

    String controllerIp = "0.0.0.0/0";
    int agentPort = controllerServices.getDefaultAgentPort();

    // check if any one of the security group
    // already has agent port and controller ip
    List<SecurityGroup> securityGroups = describeSecurityGroupsResult.getSecurityGroups();
    for (SecurityGroup securityGroup : securityGroups) {
        List<IpPermission> ipPermissions = securityGroup.getIpPermissions();
        for (IpPermission permission : ipPermissions) {
            if (permission.getIpRanges().contains(controllerIp)
                    && (agentPort >= permission.getFromPort() &&
                    agentPort <= permission.getToPort())) {
                return;
            }
        }
    }

    String securityGroupIdOrName = null;

    if (withNames) {

        if (securityGroupNamesOrIds.contains(Utils.DEFAULT_SECURITY_GROUP)) {
            securityGroupIdOrName = Utils.DEFAULT_SECURITY_GROUP;
        } else {
            securityGroupIdOrName = securityGroups.get(0).getGroupName();
        }
    } else {
        securityGroupIdOrName = securityGroups.get(0).getGroupId();
    }

    IpPermission ipPermission = new IpPermission();
    ipPermission.setFromPort(agentPort);
    ipPermission.setToPort(agentPort);
    ipPermission.setIpProtocol("tcp");
    ipPermission.setIpRanges(Lists.newArrayList(controllerIp));

    AuthorizeSecurityGroupIngressRequest securityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();
    securityGroupIngressRequest.withIpPermissions(ipPermission);

    if (withNames) {
        securityGroupIngressRequest.withGroupName(securityGroupIdOrName);
    } else {
        securityGroupIngressRequest.withGroupId(securityGroupIdOrName);
    }


    connector.authorizeSecurityGroupIngress(securityGroupIngressRequest);
}
项目:datamung    文件:CreateJobPages.java   
private ModelAndView showWorkerInstanceOptions( JobInput input )
    throws IOException
{
    if ( input.getWorkerInstanceOptions() == null )
    {
        WorkerInstanceOptions defaultOptions = new WorkerInstanceOptions();

        input.setWorkerInstanceOptions( defaultOptions );
    }
    ModelAndView mav =
        new ModelAndView( "create/worker_options.vm" ).addObject( "input",
                                                                  input ).addObject( "inputData",
                                                                                     input.serializeTo() );
    AWSCredentials creds =
        new BasicAWSCredentials( input.getAwsAccessKeyId(),
                                 input.getAwsSecretKey() );

    // Fetch all keypairs
    mav.addObject( "allKeyPairs",
                   ec2.describeKeyPairs( decorate( new DescribeKeyPairsRequest(),
                                                   creds ) ).getKeyPairs() );

    // Fetch all security groups
    String vpcId = null;
    switch ( input.getActionType() )
    {
        case BACKUP_INSTANCE:
            DBInstance instance =
                rds.describeDBInstances( decorate( new DescribeDBInstancesRequest().withDBInstanceIdentifier( input.getSourceAndDestination().getDatabaseInstanceId() ),
                                                   creds ) ).getDBInstances().get( 0 );
            mav.addObject( "sourceDatabaseInstance", instance );
            if ( instance.getDBSubnetGroup() != null )
            {
                vpcId = instance.getDBSubnetGroup().getVpcId();
            }
            break;
        case CONVERT_SNAPSHOT:
            DBSnapshot snapshot =
                rds.describeDBSnapshots( decorate( new DescribeDBSnapshotsRequest().withDBSnapshotIdentifier( input.getSourceAndDestination().getDatabaseSnapshotId() ),
                                                   creds ) ).getDBSnapshots().get( 0 );
            mav.addObject( "sourceDatabaseSnapshot", snapshot );
            vpcId = snapshot.getVpcId();
            break;
        default:
            throw new IllegalStateException( "Action type "
                + input.getActionType() + " is not expected" );
    }
    mav.addObject( "vpcId", vpcId );

    List<SecurityGroup> availableGroups = new ArrayList<SecurityGroup>();
    for ( SecurityGroup group : ec2.describeSecurityGroups( decorate( new DescribeSecurityGroupsRequest(),
                                                                      creds ) ).getSecurityGroups() )
    {
        if ( StringUtils.equals( vpcId, group.getVpcId() )
            && !group.getGroupName().startsWith( "awseb-e-" ) )
        {
            availableGroups.add( group );
        }
    }
    mav.addObject( "allSecurityGroups", availableGroups );

    if ( vpcId != null )
    {
        List<Subnet> availableSubnets = new ArrayList<Subnet>();
        for ( Subnet subnet : ec2.describeSubnets( decorate( new DescribeSubnetsRequest(),
                                                             creds ) ).getSubnets() )
        {
            if ( StringUtils.equals( subnet.getVpcId(), vpcId ) )
            {
                availableSubnets.add( subnet );
            }
        }
        mav.addObject( "allSubnets", availableSubnets );
    }

    mav.addObject( "workerOptions", input.getWorkerInstanceOptions() );
    return mav;
}
项目:aws-sdk-java-resources    文件:Vpc.java   
/**
 * Retrieves the SecurityGroups collection referenced by this resource.
 */
SecurityGroupCollection getSecurityGroups(DescribeSecurityGroupsRequest
        request);
项目:aws-sdk-java-resources    文件:SecurityGroup.java   
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet.
 * The following request parameters will be populated from the data of this
 * <code>SecurityGroup</code> resource, and any conflicting parameter value
 * set in the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>GroupIds.0</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see DescribeSecurityGroupsRequest
 */
boolean load(DescribeSecurityGroupsRequest request);