Example usage for com.amazonaws.services.ec2.model UserIdGroupPair UserIdGroupPair

List of usage examples for com.amazonaws.services.ec2.model UserIdGroupPair UserIdGroupPair

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model UserIdGroupPair UserIdGroupPair.

Prototype

UserIdGroupPair

Source Link

Usage

From source file:com.lunabeat.dooper.HadoopCluster.java

License:Apache License

/**
 *
 *//*from ww w .  ja  v  a  2  s.c  o m*/
public void createSecurityGroups() {
    if (groupsExist()) {
        return;
    }
    String portList = _config.get(ClusterConfig.WEB_PORTS_KEY);

    List<Integer> webPorts = new ArrayList<Integer>();
    if (!"0".contentEquals(portList)) {
        String[] portParts = portList.split(",");
        for (String portString : portParts) {
            try {
                webPorts.add(Integer.parseInt(portString));
            } catch (NumberFormatException e) {
                throw new RuntimeException(
                        ClusterConfig.WEB_PORTS_KEY + " config value must be list of ints or '0'");
            }
        }
    }
    UserIdGroupPair slaveUserIdGroupPair = new UserIdGroupPair().withGroupName(_groupName)
            .withUserId(_config.get(ClusterConfig.ACCOUNT_ID_KEY));
    UserIdGroupPair masterUserIdGroupPair = new UserIdGroupPair().withGroupName(_masterGroupName)
            .withUserId(_config.get(ClusterConfig.ACCOUNT_ID_KEY));
    CreateSecurityGroupRequest masterCsr = new CreateSecurityGroupRequest().withGroupName(_masterGroupName)
            .withDescription("Master group created by hadooper-pooper.");
    _ec2.createSecurityGroup(masterCsr);
    CreateSecurityGroupRequest slaveCsr = new CreateSecurityGroupRequest().withGroupName(_groupName)
            .withDescription("Slave group created by hadooper-pooper.");
    _ec2.createSecurityGroup(slaveCsr);
    ArrayList<IpPermission> ipPerms = new ArrayList<IpPermission>();
    ipPerms.add(new IpPermission().withToPort(22).withFromPort(22).withIpProtocol(TCP).withIpRanges(ALL_IPS));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(TCP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(UDP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(ICMP)
            .withToPort(-1).withFromPort(-1));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(TCP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(UDP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(ICMP)
            .withToPort(-1).withFromPort(-1));

    for (int port : webPorts) {
        LOGGER.info("Adding port " + port + " to security group.");
        ipPerms.add(new IpPermission().withToPort(port).withFromPort(port).withIpProtocol(TCP)
                .withIpRanges(ALL_IPS));
    }

    AuthorizeSecurityGroupIngressRequest masterASR = new AuthorizeSecurityGroupIngressRequest()
            .withGroupName(_masterGroupName).withIpPermissions(ipPerms);
    _ec2.authorizeSecurityGroupIngress(masterASR);

    AuthorizeSecurityGroupIngressRequest asr = new AuthorizeSecurityGroupIngressRequest()
            .withGroupName(_groupName).withIpPermissions(ipPerms);
    _ec2.authorizeSecurityGroupIngress(asr);

}

From source file:com.lunabeat.dooper.HadoopCluster.java

License:Apache License

/**
 *
 * @return boolean success//from  www.ja v  a 2s.c  o m
 */
public boolean removeSecurityGroups() {
    if (!groupsExist()) {
        return true;
    }
    if (_master != null || _slaves.size() > 0) {
        return false;
    }
    UserIdGroupPair slaveUserIdGroupPair = new UserIdGroupPair().withGroupName(_groupName)
            .withUserId(_config.get(ClusterConfig.ACCOUNT_ID_KEY));
    UserIdGroupPair masterUserIdGroupPair = new UserIdGroupPair().withGroupName(_masterGroupName)
            .withUserId(_config.get(ClusterConfig.ACCOUNT_ID_KEY));
    ArrayList<IpPermission> ipPerms = new ArrayList<IpPermission>();
    ipPerms.add(new IpPermission().withToPort(22).withFromPort(22).withIpProtocol(TCP).withIpRanges(ALL_IPS));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(TCP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(UDP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(masterUserIdGroupPair).withIpProtocol(ICMP)
            .withToPort(-1).withFromPort(-1));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(TCP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(UDP)
            .withToPort(HI_PORT).withFromPort(LOW_PORT));
    ipPerms.add(new IpPermission().withUserIdGroupPairs(slaveUserIdGroupPair).withIpProtocol(ICMP)
            .withToPort(-1).withFromPort(-1));
    RevokeSecurityGroupIngressRequest srsgi = new RevokeSecurityGroupIngressRequest().withGroupName(_groupName)
            .withIpPermissions(ipPerms);
    _ec2.revokeSecurityGroupIngress(srsgi);
    RevokeSecurityGroupIngressRequest mrsgi = new RevokeSecurityGroupIngressRequest()
            .withGroupName(_masterGroupName).withIpPermissions(ipPerms);
    _ec2.revokeSecurityGroupIngress(mrsgi);
    _ec2.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName(_groupName));
    _ec2.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName(_masterGroupName));
    return true;
}

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

License:Apache License

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

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

License:Apache License

default void addClassicLinkIngress(SecurityGroupLookup lookup, String classicLinkGroupName, String groupId,
        NetflixAmazonCredentials credentials, String vpcId) {
    if (classicLinkGroupName == null) {
        return;/*from   ww w .jav  a 2 s .  c  om*/
    }
    lookup.getSecurityGroupById(credentials.getName(), groupId, vpcId).ifPresent(targetGroupUpdater -> {
        SecurityGroup targetGroup = targetGroupUpdater.getSecurityGroup();
        lookup.getSecurityGroupByName(credentials.getName(), classicLinkGroupName, vpcId)
                .map(updater -> updater.getSecurityGroup().getGroupId()).ifPresent(classicLinkGroupId -> {
                    // don't attach if there's already some rule already configured
                    if (targetGroup.getIpPermissions().stream().anyMatch(p -> p.getUserIdGroupPairs().stream()
                            .anyMatch(p2 -> p2.getGroupId().equals(classicLinkGroupId)))) {
                        return;
                    }
                    targetGroupUpdater
                            .addIngress(Collections.singletonList(
                                    new IpPermission().withIpProtocol("tcp").withFromPort(80).withToPort(65535)
                                            .withUserIdGroupPairs(new UserIdGroupPair()
                                                    .withUserId(credentials.getAccountId())
                                                    .withGroupId(classicLinkGroupId).withVpcId(vpcId))));
                });
    });
}

From source file:com.netflix.spinnaker.clouddriver.aws.deploy.ops.loadbalancer.IngressLoadBalancerBuilder.java

License:Apache License

private IpPermission newIpPermissionWithSourceAndPort(String sourceGroupId, int port) {
    return new IpPermission().withIpProtocol("tcp").withFromPort(port).withToPort(port)
            .withUserIdGroupPairs(new UserIdGroupPair().withGroupId(sourceGroupId));
}

From source file:com.norbl.cbp.ppe.SecurityGroupFactory.java

License:Open Source License

private IpPermission createIPPermissionGroup(String protocol, int fromPort, int toPort, String group) {
    IpPermission ipp = new IpPermission();
    ipp.setIpProtocol(protocol);/* w w  w.j a v a 2s .c o  m*/
    ipp.setFromPort(fromPort);
    ipp.setToPort(toPort);

    List<UserIdGroupPair> gps = new ArrayList<UserIdGroupPair>();
    UserIdGroupPair gp = new UserIdGroupPair();
    gp.setGroupName(group);
    gp.setUserId(params.getAWSUserID());
    gps.add(gp);

    ipp.setUserIdGroupPairs(gps);

    return (ipp);
}

From source file:de.unibi.cebitec.bibigrid.meta.aws.CreateClusterEnvironmentAWS.java

@Override
public CreateClusterEnvironmentAWS createSecurityGroup() {
    CreateTagsRequest tagRequest = new CreateTagsRequest();
    tagRequest.withResources(subnet.getSubnetId()).withTags(cluster.getBibigridid(),
            new Tag("Name", SUBNET_PREFIX + cluster.getClusterId()));
    cluster.getEc2().createTags(tagRequest);

    ///////////////////////////////////////////////////////////////////////
    ///// MASTERIP
    MASTERIP = SubNets.getFirstIP(subnet.getCidrBlock());

    ////////////////////////////////////////////////////////////////////////
    ///// create security group with full internal access / ssh from outside
    log.info("Creating security group...");

    CreateSecurityGroupRequest secReq = new CreateSecurityGroupRequest();
    secReq.withGroupName(SECURITY_GROUP_PREFIX + cluster.getClusterId()).withDescription(cluster.getClusterId())
            .withVpcId(vpc.getVpcId());/*from  w  w  w  . j  a  v  a2  s .c  o  m*/
    secReqResult = cluster.getEc2().createSecurityGroup(secReq);

    log.info(V, "security group id: {}", secReqResult.getGroupId());

    UserIdGroupPair secGroupSelf = new UserIdGroupPair().withGroupId(secReqResult.getGroupId());

    IpPermission secGroupAccessSsh = new IpPermission();
    secGroupAccessSsh.withIpProtocol("tcp").withFromPort(22).withToPort(22).withIpRanges("0.0.0.0/0");
    IpPermission secGroupSelfAccessTcp = new IpPermission();
    secGroupSelfAccessTcp.withIpProtocol("tcp").withFromPort(0).withToPort(65535)
            .withUserIdGroupPairs(secGroupSelf);
    IpPermission secGroupSelfAccessUdp = new IpPermission();
    secGroupSelfAccessUdp.withIpProtocol("udp").withFromPort(0).withToPort(65535)
            .withUserIdGroupPairs(secGroupSelf);
    IpPermission secGroupSelfAccessIcmp = new IpPermission();
    secGroupSelfAccessIcmp.withIpProtocol("icmp").withFromPort(-1).withToPort(-1)
            .withUserIdGroupPairs(secGroupSelf);

    List<IpPermission> allIpPermissions = new ArrayList<>();
    allIpPermissions.add(secGroupAccessSsh);
    allIpPermissions.add(secGroupSelfAccessTcp);
    allIpPermissions.add(secGroupSelfAccessUdp);
    allIpPermissions.add(secGroupSelfAccessIcmp);
    for (Port port : cluster.getConfig().getPorts()) {
        log.info("{}:{}", port.iprange, "" + port.number);
        IpPermission additionalPortTcp = new IpPermission();
        additionalPortTcp.withIpProtocol("tcp").withFromPort(port.number).withToPort(port.number)
                .withIpRanges(port.iprange);
        allIpPermissions.add(additionalPortTcp);
        IpPermission additionalPortUdp = new IpPermission();
        additionalPortUdp.withIpProtocol("udp").withFromPort(port.number).withToPort(port.number)
                .withIpRanges(port.iprange);
        allIpPermissions.add(additionalPortUdp);
    }

    AuthorizeSecurityGroupIngressRequest ruleChangerReq = new AuthorizeSecurityGroupIngressRequest();
    ruleChangerReq.withGroupId(secReqResult.getGroupId()).withIpPermissions(allIpPermissions);

    tagRequest = new CreateTagsRequest();
    tagRequest.withResources(secReqResult.getGroupId()).withTags(cluster.getBibigridid(),
            new Tag("Name", SECURITY_GROUP_PREFIX + cluster.getClusterId()));
    cluster.getEc2().createTags(tagRequest);

    cluster.getEc2().authorizeSecurityGroupIngress(ruleChangerReq);

    return this;
}

From source file:jp.primecloud.auto.aws.typica.converter.UserIdGroupPairConverter.java

License:Open Source License

@Override
protected UserIdGroupPair convertObject(String[] from) {
    UserIdGroupPair to = new UserIdGroupPair();

    to.setUserId(from[0]);//from   www .  j  ava2  s  .  c  om
    to.setGroupName(from[1]);

    return to;
}

From source file:n3phele.factory.ec2.VirtualServerResource.java

License:Open Source License

private boolean makeSecurityGroup(String groupName, String id, String secret, URI location, String to,
        String firstName, String lastName) {
    AmazonEC2Client client = null;//from  w  w w  .  j  a  va2  s. co m
    client = getEC2Client(id, secret, location);
    boolean found = true;
    boolean failed = false;
    try {
        client.createSecurityGroup(new CreateSecurityGroupRequest().withGroupName("n3phele-" + groupName)
                .withDescription("n3phele " + groupName + " security group"));

        String ownerId = null;
        DescribeSecurityGroupsResult newGroupResult = client.describeSecurityGroups();
        for (SecurityGroup g : newGroupResult.getSecurityGroups()) {
            if (g.getGroupName().equals("n3phele-" + groupName)) {
                ownerId = g.getOwnerId();
            }
        }
        if (ownerId == null)
            return false;
        log.info("found ownerId of " + ownerId);

        log.info("adding ssh ports");
        try {
            client.authorizeSecurityGroupIngress(
                    new AuthorizeSecurityGroupIngressRequest().withGroupName("n3phele-" + groupName)
                            .withCidrIp("0.0.0.0/0").withIpProtocol("tcp").withFromPort(22).withToPort(22));
        } catch (Exception e) {
            log.log(Level.SEVERE, "Create security group " + groupName, e);
            failed = true;
        }

        log.info("adding agent ports");
        try {
            client.authorizeSecurityGroupIngress(
                    new AuthorizeSecurityGroupIngressRequest().withGroupName("n3phele-" + groupName)
                            .withCidrIp("0.0.0.0/0").withIpProtocol("tcp").withFromPort(8887).withToPort(8887));
        } catch (Exception e) {
            log.log(Level.SEVERE, "Create security group " + groupName, e);
            failed = true;
        }

        if (!failed) {
            log.info("adding self access");

            try {
                List<IpPermission> permissions = new ArrayList<IpPermission>();

                UserIdGroupPair userIdGroupPairs = new UserIdGroupPair().withUserId(ownerId)
                        .withGroupName("n3phele-" + groupName);

                permissions.add(new IpPermission().withIpProtocol("icmp").withFromPort(-1).withToPort(-1)
                        .withUserIdGroupPairs(userIdGroupPairs));

                permissions.add(new IpPermission().withIpProtocol("tcp").withFromPort(1).withToPort(65535)
                        .withUserIdGroupPairs(userIdGroupPairs));

                permissions.add(new IpPermission().withIpProtocol("udp").withFromPort(1).withToPort(65535)
                        .withUserIdGroupPairs(userIdGroupPairs));

                log.info("adding icmp/tcp/udp");

                client.authorizeSecurityGroupIngress(
                        new AuthorizeSecurityGroupIngressRequest("n3phele-" + groupName, permissions));
            } catch (Exception e) {
                log.log(Level.WARNING, "Error adding self access to group " + groupName, e);
            }
        }

        if (failed) {
            client.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName("n3phele-" + groupName));
            found = false;
        } else {
            sendSecurityGroupNotificationEmail("n3phele-" + groupName, to, firstName, lastName, location);
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Create security group " + groupName, e);
        client.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName("n3phele-" + groupName));
        found = false;
    }
    return found;
}

From source file:org.openinfinity.cloud.service.administrator.EC2Wrapper.java

License:Apache License

public void authorizeGroup(String securityGroupName, String sourceGroupName, String sourceGroupOwner,
        Integer fromPort, Integer toPort, String protocol) {
    try {/*from w  ww.ja va2s .  c  om*/
        AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest();
        //   if(this.cloudType == InstanceService.CLOUD_TYPE_EUCALYPTUS) {
        /*      request.setFromPort(fromPort);
              request.setToPort(toPort);
              request.setSourceSecurityGroupName(sourceGroupName);
              request.setSourceSecurityGroupOwnerId(sourceGroupOwner);
              request.setIpProtocol(protocol); */
        //      } else {

        UserIdGroupPair pair = new UserIdGroupPair();
        pair.setGroupName(sourceGroupName);
        pair.setUserId(sourceGroupOwner);
        List<UserIdGroupPair> idList = new ArrayList<UserIdGroupPair>();
        idList.add(pair);
        IpPermission perm = new IpPermission();
        perm.setUserIdGroupPairs(idList);
        perm.setFromPort(fromPort);
        perm.setToPort(toPort);
        perm.setIpProtocol(protocol);
        List<IpPermission> permList = new ArrayList<IpPermission>();
        permList.add(perm);
        request.setIpPermissions(permList);
        //      }
        request.setGroupName(securityGroupName);

        ec2.authorizeSecurityGroupIngress(request);
    } catch (Exception e) {
        String message = e.getMessage();
        LOG.error("Could not set authorized IP:s to security group: " + message);
        ExceptionUtil.throwSystemException(message, e);
    }
}