com.amazonaws.services.rds.model.DBCluster Java Examples

The following examples show how to use com.amazonaws.services.rds.model.DBCluster. 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: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch RDS cluster info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<DBClusterVH>> fetchRDSClusterInfo(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	Map<String,List<DBClusterVH>> rdsMap =  new LinkedHashMap<>();
	AmazonRDS rdsClient ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"RDS Cluster\" , \"region\":\"" ;
	for(Region region : RegionUtils.getRegions()){
		try{
			if(!skipRegions.contains(region.getName())){
				rdsClient = AmazonRDSClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeDBClustersResult rslt ;
				String nextMarker = null;
				List<DBClusterVH> rdsList = new ArrayList<>();
				do{
					rslt = rdsClient.describeDBClusters( new DescribeDBClustersRequest().withMarker(nextMarker));
					List<DBCluster> rdsListTemp = rslt.getDBClusters();
					for(DBCluster cluster : rdsListTemp){
						DBClusterVH vh = new DBClusterVH(cluster,rdsClient.listTagsForResource(new ListTagsForResourceRequest().
								withResourceName(cluster.getDBClusterArn())).
								getTagList());
						rdsList.add(vh);
					}
					nextMarker = rslt.getMarker();
				}while(nextMarker!=null);

				if( !rdsList.isEmpty() ){
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : RDS Cluster "+region.getName() + " >> "+rdsList.size());
					rdsMap.put(accountId+delimiter+accountName+delimiter+region.getName(), rdsList);
				}
			}
		}catch(Exception e){
			if(region.isServiceSupported(AmazonRDS.ENDPOINT_PREFIX)){
				log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
				ErrorManageUtil.uploadError(accountId,region.getName(),"rdscluster",e.getMessage());
			}
		}
	}
	return rdsMap;
}
 
Example #2
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch RDS cluster info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchRDSClusterInfoTest() throws Exception {
    
    mockStatic(AmazonRDSClientBuilder.class);
    AmazonRDS rdsClient = PowerMockito.mock(AmazonRDS.class);
    AmazonRDSClientBuilder amazonRDSClientBuilder = PowerMockito.mock(AmazonRDSClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonRDSClientBuilder.standard()).thenReturn(amazonRDSClientBuilder);
    when(amazonRDSClientBuilder.withCredentials(anyObject())).thenReturn(amazonRDSClientBuilder);
    when(amazonRDSClientBuilder.withRegion(anyString())).thenReturn(amazonRDSClientBuilder);
    when(amazonRDSClientBuilder.build()).thenReturn(rdsClient);
    
    DescribeDBClustersResult describeDBClustersResult = new DescribeDBClustersResult();
    List<DBCluster> rdsList = new ArrayList<>();
    DBCluster dBCluster = new DBCluster();
    dBCluster.setDBClusterArn("dBClusterArn");;
    rdsList.add(dBCluster);
    describeDBClustersResult.setDBClusters(rdsList);
    when(rdsClient.describeDBClusters(anyObject())).thenReturn(describeDBClustersResult);
    
    ListTagsForResourceResult listTagsForResourceResult = new ListTagsForResourceResult();
    listTagsForResourceResult.setTagList(new ArrayList<>());
    when(rdsClient.listTagsForResource(anyObject())).thenReturn(listTagsForResourceResult);
    assertThat(inventoryUtil.fetchRDSClusterInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #3
Source File: DatabaseConnectionService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
public String checkDb(DBCluster db, AWSEnvironment awsEnvironment) throws GKUnsupportedDBException{
    Account account = accountInformationService.getAccountByAlias(awsEnvironment.getAccount());
    List<String> issues = databaseConnectionFactory.getConnection(db.getEngine()).checkDb(
            new RdsQuery()
                    .withAccount(account.getAlias())
                    .withAccountId(account.getAccountId())
                    .withRegion(awsEnvironment.getRegion())
                    .withSdlc(awsEnvironment.getSdlc())
                    .withAddress(getAddress(String.format("%s:%s", db.getEndpoint(), db.getPort()), db.getDatabaseName()))
                    .withDbInstanceName(db.getDBClusterIdentifier())
    );
    return issues.stream().collect(Collectors.joining(","));
}
 
Example #4
Source File: DatabaseConnectionService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
public List<String> getAvailableRolesForDb(DBCluster db, AWSEnvironment awsEnvironment) throws Exception {
    Account account = accountInformationService.getAccountByAlias(awsEnvironment.getAccount());
    return databaseConnectionFactory.getConnection(db.getEngine()).getAvailableRoles( new RdsQuery()
            .withAccount(account.getAlias())
            .withAccountId(account.getAccountId())
            .withRegion(awsEnvironment.getRegion())
            .withSdlc(awsEnvironment.getSdlc())
            .withAddress(getAddress(String.format("%s:%s", db.getEndpoint(), db.getPort()), db.getDatabaseName()))
            .withDbInstanceName(db.getDBClusterIdentifier()));
}
 
Example #5
Source File: RevokeAccessServiceTask.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
/***
 * @param execution - the request to execute on
 * @throws Exception - if the revocation fails
 */
public void execute(DelegateExecution execution) throws Exception{
    Job job = managementService.createJobQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
    AccessRequest accessRequest = (AccessRequest)execution.getVariable("accessRequest");
    try {
        AWSEnvironment awsEnvironment = new AWSEnvironment(accessRequest.getAccount(), accessRequest.getRegion(), accessRequest.getAccountSdlc());
        logger.info("Revoking access for Users, Attempts remaining: " + job.getRetries());
        for(User user : accessRequest.getUsers()){
            for(UserRole role : accessRequest.getRoles()) {
                AWSRdsDatabase database = accessRequest.getAwsRdsInstances().get(0);
                // if the db was actually an aurora global cluster then we should re-fetch the primary cluster
                // as that could have changed
                if(database.getDatabaseType() != null && database.getDatabaseType() == DatabaseType.AURORA_GLOBAL){
                    logger.info("Re-fetching the Primary Cluster for this global cluster since it could have changed over time.");
                    DBCluster primaryCluster = rdsLookupService.getPrimaryClusterForGlobalCluster(awsEnvironment, database.getName()).get();
                    database.setEndpoint(String.format("%s:%s", primaryCluster.getEndpoint(), primaryCluster.getPort()));
                }
                databaseConnectionService.revokeAccess(database, awsEnvironment, RoleType.valueOf(role.getRole().toUpperCase()), user.getUserId());
            }
        }

    }catch(Exception e){
        if(job.getRetries() - 1 == 0){
            logger.error("Maximum attempt limit reached. Notify Ops team for manual removal");
            emailServiceWrapper.notifyOps(accessRequest);
            emailServiceWrapper.notifyAdminsOfFailure(accessRequest,e);
        }else{
            throw e;
        }
    }
}
 
Example #6
Source File: RDSInstance.java    From billow with Apache License 2.0 5 votes vote down vote up
public static boolean checkIfMaster(DBInstance instance, DBCluster cluster) {
    if (instance.getDBClusterIdentifier() == null || cluster == null) {
        // It's NOT a member of a DB cluster
        return instance.getReadReplicaSourceDBInstanceIdentifier() == null;
    } else {
        // It's a member of a DB cluster
        for (DBClusterMember member : cluster.getDBClusterMembers()) {
            if (member.getDBInstanceIdentifier().equals(instance.getDBInstanceIdentifier()) && member.isClusterWriter()) {
                return true;
            }
        }
        return false;
    }
}
 
Example #7
Source File: RDSInstance.java    From billow with Apache License 2.0 4 votes vote down vote up
public RDSInstance(DBInstance instance, DBCluster cluster, List<Tag> tagList, List<String> snapshots) {
    this.allocatedStorage = instance.getAllocatedStorage();
    this.autoMinorVersionUpgrade = instance.getAutoMinorVersionUpgrade();
    this.availabilityZone = instance.getAvailabilityZone();
    this.backupRetentionPeriod = instance.getBackupRetentionPeriod();
    this.characterSetName = instance.getCharacterSetName();
    this.dBInstanceClass = instance.getDBInstanceClass();
    this.dBInstanceIdentifier = instance.getDBInstanceIdentifier();
    this.dBInstanceStatus = instance.getDBInstanceStatus();
    this.dBClusterIdentifier = instance.getDBClusterIdentifier();
    this.dBName = instance.getDBName();
    this.dBParameterGroups = instance.getDBParameterGroups();
    this.dBSecurityGroups = instance.getDBSecurityGroups();
    this.dBSubnetGroup = instance.getDBSubnetGroup();
    this.endpoint = instance.getEndpoint();
    if(this.endpoint != null) {
      this.hostname = endpoint.getAddress();
      this.privateIP = getPrivateIp(hostname);
    } else {
      this.hostname = null;
      this.privateIP = null;
    }
    this.engine = instance.getEngine();
    this.engineVersion = instance.getEngineVersion();
    this.instanceCreateTime = instance.getInstanceCreateTime();
    this.iops = instance.getIops();
    this.latestRestorableTime = instance.getLatestRestorableTime();
    this.licenseModel = instance.getLicenseModel();
    this.masterUsername = instance.getMasterUsername();
    this.multiAZ = instance.getMultiAZ();
    this.optionGroupMemberships = instance.getOptionGroupMemberships();
    this.pendingModifiedValues = instance.getPendingModifiedValues();
    this.preferredBackupWindow = instance.getPreferredBackupWindow();
    this.preferredMaintenanceWindow = instance.getPreferredMaintenanceWindow();
    this.publiclyAccessible = instance.getPubliclyAccessible();
    this.readReplicaDBInstanceIdentifiers = instance.getReadReplicaDBInstanceIdentifiers();
    this.readReplicaSourceDBInstanceIdentifier = instance.getReadReplicaSourceDBInstanceIdentifier();
    this.secondaryAvailabilityZone = instance.getSecondaryAvailabilityZone();
    this.statusInfos = instance.getStatusInfos();
    this.vpcSecurityGroups = instance.getVpcSecurityGroups();
    this.isMaster = checkIfMaster(instance, cluster);

    this.tags = new HashMap<>(tagList.size());
    for(Tag tag : tagList) {
        this.tags.put(tag.getKey(), tag.getValue());
    }

    this.snapshots = new ArrayList<>(snapshots);
    this.caCertificateIdentifier = instance.getCACertificateIdentifier();
}
 
Example #8
Source File: DBClusterVH.java    From pacbot with Apache License 2.0 2 votes vote down vote up
/**
 * Instantiates a new DB cluster VH.
 *
 * @param cluster the cluster
 * @param tags the tags
 */
public DBClusterVH(DBCluster cluster, List<Tag> tags){
	this.cluster = cluster;
	this.tags = tags;
}
 
Example #9
Source File: DBClusterVH.java    From pacbot with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the cluster.
 *
 * @return the cluster
 */
public DBCluster getCluster() {
	return cluster;
}