Java Code Examples for com.amazonaws.services.rds.model.DBInstance

The following examples show how to use com.amazonaws.services.rds.model.DBInstance. These examples are extracted from open source projects. 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
/**
 * Calls DescribeDBInstances on the AWS RDS Client returning all DB Instances that match the supplied predicate and attempting
 * to push down certain predicates (namely queries for specific DB Instance) to EC2.
 *
 * @See TableProvider
 */
@Override
public void readWithConstraint(BlockSpiller spiller, ReadRecordsRequest recordsRequest, QueryStatusChecker queryStatusChecker)
{
    boolean done = false;
    DescribeDBInstancesRequest request = new DescribeDBInstancesRequest();

    ValueSet idConstraint = recordsRequest.getConstraints().getSummary().get("instance_id");
    if (idConstraint != null && idConstraint.isSingleValue()) {
        request.setDBInstanceIdentifier(idConstraint.getSingleValue().toString());
    }

    while (!done) {
        DescribeDBInstancesResult response = rds.describeDBInstances(request);

        for (DBInstance instance : response.getDBInstances()) {
            instanceToRow(instance, spiller);
        }

        request.setMarker(response.getMarker());

        if (response.getMarker() == null || !queryStatusChecker.isQueryRunning()) {
            done = true;
        }
    }
}
 
Example 2
@Override
protected void setUpRead()
{
    final AtomicLong requestCount = new AtomicLong(0);
    when(mockRds.describeDBInstances(any(DescribeDBInstancesRequest.class)))
            .thenAnswer((InvocationOnMock invocation) -> {
                DescribeDBInstancesResult mockResult = mock(DescribeDBInstancesResult.class);
                List<DBInstance> values = new ArrayList<>();
                values.add(makeValue(getIdValue()));
                values.add(makeValue(getIdValue()));
                values.add(makeValue("fake-id"));
                when(mockResult.getDBInstances()).thenReturn(values);

                if (requestCount.incrementAndGet() < 3) {
                    when(mockResult.getMarker()).thenReturn(String.valueOf(requestCount.get()));
                }
                return mockResult;
            });
}
 
Example 3
Source Project: obevo   Source File: CreateDbInstance.java    License: Apache License 2.0 6 votes vote down vote up
public void createOracle(String dbInstanceIdentifier) throws Exception {
    // http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html
    CreateDBInstanceRequest request = new CreateDBInstanceRequest()
            .withEngine("oracle-se2")
            //.withEngineVersion("12.1.0.2.v8")
            .withLicenseModel("license-included")
            .withAllocatedStorage(10)
            .withStorageType("gp2")  // SSD
            .withBackupRetentionPeriod(0)
            .withDBInstanceClass("db.t2.micro")
            .withDBInstanceIdentifier(dbInstanceIdentifier)
            .withDBName("DBDEPLOY")
            .withMasterUsername("deploybuilddbo")
            .withMasterUserPassword("deploybuilddb0")
            //.withVpcSecurityGroupIds("default")
            ;
    DBInstance response = client.createDBInstance(request);
    System.out.println(response);

    describe(dbInstanceIdentifier);
}
 
Example 4
Source Project: obevo   Source File: CreateDbInstance.java    License: Apache License 2.0 6 votes vote down vote up
public void createPostgresql(String dbInstanceIdentifier) throws Exception {
    // http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html
    CreateDBInstanceRequest request = new CreateDBInstanceRequest()
            .withEngine("postgres")
            .withEngineVersion("9.6.2")
            .withLicenseModel("postgresql-license")
            .withAllocatedStorage(5)
            .withStorageType("gp2")  // SSD
            .withBackupRetentionPeriod(0)
            .withDBInstanceClass("db.t2.micro")
            .withDBInstanceIdentifier(dbInstanceIdentifier)
            .withDBName("DBDEPLOY")
            .withMasterUsername("deploybuilddbo")
            .withMasterUserPassword("deploybuilddb0");
    DBInstance response = client.createDBInstance(request);
    System.out.println(response);

    describe(dbInstanceIdentifier);
}
 
Example 5
Source Project: obevo   Source File: CreateDbInstance.java    License: Apache License 2.0 6 votes vote down vote up
private void createSqlServer(String dbInstanceIdentifier) throws Exception {
    // http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html
    CreateDBInstanceRequest request = new CreateDBInstanceRequest()
            .withEngine("sqlserver-ex")
            .withEngineVersion("13.00.2164.0.v1")
            .withLicenseModel("license-included")
            .withAllocatedStorage(20)
            .withStorageType("gp2")  // SSD
            .withBackupRetentionPeriod(0)
            .withDBInstanceClass("db.t2.micro")
            .withDBInstanceIdentifier(dbInstanceIdentifier)
            //.withDBName("DBDEPLOY")
            .withMasterUsername("deploybuilddbo")
            .withMasterUserPassword("deploybuilddb0");
    DBInstance response = client.createDBInstance(request);
    System.out.println(response);

    describe(dbInstanceIdentifier);
}
 
Example 6
Source Project: obevo   Source File: CreateDbInstance.java    License: Apache License 2.0 6 votes vote down vote up
private void describe(String dbInstanceIdentifier) throws Exception {
    while (true) {
        DescribeDBInstancesRequest request = new DescribeDBInstancesRequest()
                .withDBInstanceIdentifier(dbInstanceIdentifier);

        DescribeDBInstancesResult response = client.describeDBInstances(request);
        DBInstance dbInstance = response.getDBInstances().get(0);
        if (!dbInstance.getDBInstanceStatus().equalsIgnoreCase("creating")) {
            System.out.println("Done! " + response);
            System.out.println(dbInstance.getEndpoint().getAddress());
            System.out.println(dbInstance.getEndpoint().getPort());
            break;
        }

        System.out.println("Not done - will wait 10s: " + response);
        Thread.sleep(10000L);
    }
}
 
Example 7
/**
 * Retrieves the {@link com.amazonaws.services.rds.model.DBInstance} information.
 * @param identifier - the database identifier used
 * @return - the db instance
 * @throws IllegalStateException if the db instance is not found
 */
protected DBInstance getDbInstance(String identifier) throws IllegalStateException {
	DBInstance instance;
	try {
		DescribeDBInstancesResult describeDBInstancesResult = this.amazonRds
				.describeDBInstances(new DescribeDBInstancesRequest()
						.withDBInstanceIdentifier(identifier));
		instance = describeDBInstancesResult.getDBInstances().get(0);
	}
	catch (DBInstanceNotFoundException e) {
		throw new IllegalStateException(MessageFormat.format(
				"No database instance with id:''{0}'' found. Please specify a valid db instance",
				identifier));
	}
	return instance;
}
 
Example 8
@Test
void afterPropertiesSet_customUserNameSet_createsInstanceWithCustomUserNameAndIgnoresMetaDataUserName()
		throws Exception {
	AmazonRDS amazonRDS = mock(AmazonRDS.class);
	DataSourceFactory dataSourceFactory = mock(DataSourceFactory.class);

	when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest()
			.withDBInstanceIdentifier("test"))).thenReturn(
					new DescribeDBInstancesResult().withDBInstances(new DBInstance()
							.withDBInstanceStatus("available").withDBName("test")
							.withDBInstanceIdentifier("test").withEngine("mysql")
							.withMasterUsername("admin").withEndpoint(new Endpoint()
									.withAddress("localhost").withPort(3306))));

	AmazonRdsDataSourceFactoryBean amazonRdsDataSourceFactoryBean = new AmazonRdsDataSourceFactoryBean(
			amazonRDS, "test", "secret");
	amazonRdsDataSourceFactoryBean.setUsername("superAdmin");
	amazonRdsDataSourceFactoryBean.setDataSourceFactory(dataSourceFactory);
	amazonRdsDataSourceFactoryBean.afterPropertiesSet();
	amazonRdsDataSourceFactoryBean.getObject();

	verify(dataSourceFactory, times(1)).createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "superAdmin", "secret"));
}
 
Example 9
@Bean
AmazonRDS amazonRDS() {
	AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class);
	when(client.describeDBInstances(
			new DescribeDBInstancesRequest().withDBInstanceIdentifier("test")))
					.thenReturn(new DescribeDBInstancesResult().withDBInstances(
							new DBInstance().withDBInstanceStatus("available")
									.withDBName("test")
									.withDBInstanceIdentifier("test")
									.withEngine("mysql")
									.withMasterUsername("admin")
									.withEndpoint(new Endpoint()
											.withAddress("localhost")
											.withPort(3306))
									.withReadReplicaDBInstanceIdentifiers(
											"read1")));
	return client;
}
 
Example 10
@Bean
AmazonRDS amazonRDS() {
	AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class);
	when(client.describeDBInstances(
			new DescribeDBInstancesRequest().withDBInstanceIdentifier("test")))
					.thenReturn(new DescribeDBInstancesResult().withDBInstances(
							new DBInstance().withDBInstanceStatus("available")
									.withDBName("test")
									.withDBInstanceIdentifier("test")
									.withEngine("mysql")
									.withMasterUsername("admin")
									.withEndpoint(new Endpoint()
											.withAddress("localhost")
											.withPort(3306))
									.withReadReplicaDBInstanceIdentifiers(
											"read1")));
	return client;
}
 
Example 11
@Bean
AmazonRDS amazonRDS() {
	AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class);
	when(client.describeDBInstances(
			new DescribeDBInstancesRequest().withDBInstanceIdentifier("test")))
					.thenReturn(new DescribeDBInstancesResult().withDBInstances(
							new DBInstance().withDBInstanceStatus("available")
									.withDBName("test")
									.withDBInstanceIdentifier("test")
									.withEngine("mysql")
									.withMasterUsername("admin")
									.withEndpoint(new Endpoint()
											.withAddress("localhost")
											.withPort(3306))
									.withReadReplicaDBInstanceIdentifiers(
											"read1")));
	return client;
}
 
Example 12
@Bean
AmazonRDS amazonRDS() {
	AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class);
	when(client.describeDBInstances(
			new DescribeDBInstancesRequest().withDBInstanceIdentifier("test")))
					.thenReturn(new DescribeDBInstancesResult().withDBInstances(
							new DBInstance().withDBInstanceStatus("available")
									.withDBName("test")
									.withDBInstanceIdentifier("test")
									.withEngine("mysql")
									.withMasterUsername("admin")
									.withEndpoint(new Endpoint()
											.withAddress("localhost")
											.withPort(3306))
									.withReadReplicaDBInstanceIdentifiers(
											"read1")));
	return client;
}
 
Example 13
@Bean
AmazonRDS amazonRDS() {
	AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class);
	when(client.describeDBInstances(
			new DescribeDBInstancesRequest().withDBInstanceIdentifier("test")))
					.thenReturn(new DescribeDBInstancesResult().withDBInstances(
							new DBInstance().withDBInstanceStatus("available")
									.withDBName("test")
									.withDBInstanceIdentifier("test")
									.withEngine("mysql")
									.withMasterUsername("admin")
									.withEndpoint(new Endpoint()
											.withAddress("localhost")
											.withPort(3306))
									.withReadReplicaDBInstanceIdentifiers(
											"read1")));
	return client;
}
 
Example 14
@Test
void canRetry_retryPossibleDueToAvailableDatabase_returnsTrue() throws Exception {
	// Arrange
	AmazonRDS amazonRDS = mock(AmazonRDS.class);

	DatabaseInstanceStatusRetryPolicy policy = new DatabaseInstanceStatusRetryPolicy(
			amazonRDS, "test");
	when(amazonRDS.describeDBInstances(
			new DescribeDBInstancesRequest().withDBInstanceIdentifier("test")))
					.thenReturn(new DescribeDBInstancesResult().withDBInstances(
							new DBInstance().withDBInstanceStatus("available")));

	RetryContext retryContext = policy.open(new RetryContextSupport(null));

	// Act
	policy.registerThrowable(retryContext,
			new TransientDataAccessResourceException("not available"));

	// Assert
	assertThat(policy.canRetry(retryContext)).isTrue();
	policy.close(retryContext);
}
 
Example 15
@Bean
AmazonRDSClient amazonRDS() {
	AmazonRDSClient client = Mockito.mock(AmazonRDSClient.class);
	when(client.describeDBInstances(
			new DescribeDBInstancesRequest().withDBInstanceIdentifier("test")))
					.thenReturn(new DescribeDBInstancesResult().withDBInstances(
							new DBInstance().withDBInstanceStatus("available")
									.withDBName("test")
									.withDBInstanceIdentifier("test")
									.withEngine("mysql")
									.withMasterUsername("admin")
									.withEndpoint(new Endpoint()
											.withAddress("localhost")
											.withPort(3306))
									.withReadReplicaDBInstanceIdentifiers(
											"read1")));
	return client;
}
 
Example 16
Source Project: pacbot   Source File: RdsDbPublicAccessAutoFix.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean backupExistingConfigForResource(final String resourceId, final String resourceType, Map<String, Object> clientMap, Map<String, String> ruleParams, Map<String, String> issue) throws AutoFixException {
    StringBuilder oldConfig = new StringBuilder();
    List<DBInstance> instance;
       try {
           instance = PublicAccessAutoFix.getDBInstanceForRdsDbResource(clientMap,resourceId);

           List<VpcSecurityGroupMembership> originalSgMembers = instance.get(0).getVpcSecurityGroups();
           
           for(VpcSecurityGroupMembership sgm : originalSgMembers){
               if("active".equals(sgm.getStatus())){

                   if (oldConfig.length() > 0) {
                       oldConfig.append(",").append(sgm.getVpcSecurityGroupId());
                   } else {
                       oldConfig.append(sgm.getVpcSecurityGroupId());
                   }
               
               }
           }
       } catch (Exception e) {
           LOGGER.error("back up failed {}", e);
           throw new AutoFixException("backup failed");
       }
       DETACHED_SG = oldConfig.toString();
        backupOldConfig(resourceId, EXISTING_GROUPS, oldConfig.toString());
           LOGGER.debug("backup complete for {}" , resourceId);
           return true;
}
 
Example 17
Source Project: pacbot   Source File: PublicAccessAutoFix.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the DB instance for rds db resource.
 *
 * @param clientMap the client map
 * @param resourceId the resource id
 * @return the DB instance for rds db resource
 * @throws Exception the exception
 */
public static List<DBInstance> getDBInstanceForRdsDbResource(Map<String,Object> clientMap,String resourceId) throws Exception {
    AmazonRDS amazonRDS = (AmazonRDS) clientMap.get("client");
    DescribeDBInstancesRequest instancesRequest = new DescribeDBInstancesRequest();
    instancesRequest.setDBInstanceIdentifier(resourceId);
    DescribeDBInstancesResult dbInstancesResult = amazonRDS.describeDBInstances(instancesRequest);
    
    return dbInstancesResult.getDBInstances();

}
 
Example 18
Source Project: pacbot   Source File: DBInstanceVH.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new DB instance VH.
 *
 * @param dbinstance the dbinstance
 * @param tags the tags
 */
public DBInstanceVH(DBInstance  dbinstance, List<Tag> tags,String subnets,String securityGroups){
	this.setDbinst(dbinstance);
	this.setTags(tags);
	this.subnets =subnets;
	this.securityGroups = securityGroups;
}
 
Example 19
Source Project: pacbot   Source File: InventoryUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fetch RDS instance info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchRDSInstanceInfoTest() 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);
    
    DescribeDBInstancesResult describeDBInstancesResult = new DescribeDBInstancesResult();
    List<DBInstance> rdsList = new ArrayList<>();
    DBInstance dBInstance = new DBInstance();
    dBInstance.setDBInstanceArn("dBInstanceArn");
    rdsList.add(dBInstance);
    describeDBInstancesResult.setDBInstances(rdsList);
    when(rdsClient.describeDBInstances(anyObject())).thenReturn(describeDBInstancesResult);
    
    ListTagsForResourceResult listTagsForResourceResult = new ListTagsForResourceResult();
    listTagsForResourceResult.setTagList(new ArrayList<>());
    when(rdsClient.listTagsForResource(anyObject())).thenReturn(listTagsForResourceResult);
    assertThat(inventoryUtil.fetchRDSInstanceInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example 20
Source Project: Gatekeeper   Source File: DatabaseConnectionService.java    License: Apache License 2.0 5 votes vote down vote up
public String checkDb(DBInstance 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(db.getEndpoint(), db.getDBName()))
                    .withDbInstanceName(db.getDBInstanceIdentifier())
    );
    return issues.stream().collect(Collectors.joining(","));
}
 
Example 21
Source Project: Gatekeeper   Source File: DatabaseConnectionService.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> getAvailableRolesForDb(DBInstance 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(db.getEndpoint(), db.getDBName()))
            .withDbInstanceName(db.getDBInstanceIdentifier()));
}
 
Example 22
Source Project: fullstop   Source File: FetchRdsJob.java    License: Apache License 2.0 5 votes vote down vote up
@Scheduled(fixedRate = 300_000)
public void run() {
    for (final String accountId : allAccountIds.get()) {
        for (final String region : jobsProperties.getWhitelistedRegions()) {
            try {
                final AmazonRDSClient amazonRDSClient = clientProvider.getClient(AmazonRDSClient.class, accountId,
                        Region.getRegion(Regions.fromName(region)));

                Optional<String> marker = Optional.empty();

                do {
                    final DescribeDBInstancesRequest request = new DescribeDBInstancesRequest();
                    marker.ifPresent(request::setMarker);
                    final DescribeDBInstancesResult result = amazonRDSClient.describeDBInstances(request);
                    marker = Optional.ofNullable(trimToNull(result.getMarker()));

                    result.getDBInstances().stream()
                            .filter(DBInstance::getPubliclyAccessible)
                            .filter(dbInstance -> dbInstance.getEndpoint() != null)
                            .forEach(dbInstance -> {
                                final Map<String, Object> metadata = newHashMap();
                                metadata.put("unsecuredDatabase", dbInstance.getEndpoint().getAddress());
                                metadata.put("errorMessages", "Unsecured Database! Your DB can be reached from outside");
                                writeViolation(accountId, region, metadata, dbInstance.getEndpoint().getAddress());

                            });

                } while (marker.isPresent());

            } catch (final Exception e) {
                jobExceptionHandler.onException(e, ImmutableMap.of(
                        "job", this.getClass().getSimpleName(),
                        "aws_account_id", accountId,
                        "aws_region", region));
            }
        }
    }
}
 
Example 23
Source Project: fullstop   Source File: FetchRdsJobTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    this.clientProviderMock = mock(ClientProvider.class);
    this.jobsPropertiesMock = mock(JobsProperties.class);
    this.violationSinkMock = mock(ViolationSink.class);
    this.amazonRDSClientMock = mock(AmazonRDSClient.class);
    this.accountIdSupplierMock = mock(AccountIdSupplier.class);
    this.exceptionHandlerMock = mock(JobExceptionHandler.class);

    when(accountIdSupplierMock.get()).thenReturn(newHashSet("54321"));

    // Jobsproperties
    when(jobsPropertiesMock.getWhitelistedRegions()).thenReturn(newArrayList("eu-west-1"));

    // Dbinstances
    final Endpoint endpoint = new Endpoint();
    endpoint.setAddress("aws.db.cn");
    final Endpoint endpoint2 = new Endpoint();
    endpoint2.setAddress("aws.db2.cn");
    final DBInstance dbInstance1 = new DBInstance();
    dbInstance1.setPubliclyAccessible(true);
    dbInstance1.setEndpoint(endpoint);
    final DBInstance dbInstance2 = new DBInstance();
    dbInstance2.setPubliclyAccessible(false);
    dbInstance2.setEndpoint(endpoint);
    final DBInstance dbInstance3 = new DBInstance();
    dbInstance3.setPubliclyAccessible(true);
    dbInstance3.setEndpoint(endpoint2);
    describeDBInstancesResultMock = new DescribeDBInstancesResult();
    describeDBInstancesResultMock.setDBInstances(newArrayList(dbInstance1, dbInstance2, dbInstance3));

    // clientprovider
    when(clientProviderMock.getClient(any(), any(String.class), any(Region.class))).thenReturn(amazonRDSClientMock);

}
 
Example 24
private DataSourceInformation fromRdsInstance(DBInstance dbInstance) {
	Assert.notNull(dbInstance, "DbInstance must not be null");
	Assert.notNull(dbInstance.getEndpoint(),
			"The database instance has no endpoint available!");
	return new DataSourceInformation(DatabaseType.fromEngine(dbInstance.getEngine()),
			dbInstance.getEndpoint().getAddress(), dbInstance.getEndpoint().getPort(),
			StringUtils.hasText(this.databaseName) ? this.databaseName
					: dbInstance.getDBName(),
			StringUtils.hasText(this.username) ? this.username
					: dbInstance.getMasterUsername(),
			this.password);
}
 
Example 25
/**
 * Constructs a
 * {@link org.springframework.cloud.aws.jdbc.datasource.ReadOnlyRoutingDataSource}
 * data source that contains the regular data source as a default, and all
 * read-replicas as additional data source. The
 * {@link org.springframework.cloud.aws.jdbc.datasource.ReadOnlyRoutingDataSource} is
 * additionally wrapped with a
 * {@link org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy}, because
 * the read-only flag is only available after the transactional context has been
 * established. This is only the case if the physical connection is requested after
 * the transaction start and not while starting a transaction.
 * @return a ReadOnlyRoutingDataSource that is wrapped with a
 * LazyConnectionDataSourceProxy
 * @throws Exception if the underlying data source setup throws any exception
 */
@Override
protected DataSource createInstance() throws Exception {
	DBInstance dbInstance = getDbInstance(getDbInstanceIdentifier());

	// If there is no read replica available, delegate to super class
	if (dbInstance.getReadReplicaDBInstanceIdentifiers().isEmpty()) {
		return super.createInstance();
	}

	HashMap<Object, Object> replicaMap = new HashMap<>(
			dbInstance.getReadReplicaDBInstanceIdentifiers().size());

	for (String replicaName : dbInstance.getReadReplicaDBInstanceIdentifiers()) {
		replicaMap.put(replicaName, createDataSourceInstance(replicaName));
	}

	// Create the data source
	ReadOnlyRoutingDataSource dataSource = new ReadOnlyRoutingDataSource();
	dataSource.setTargetDataSources(replicaMap);
	dataSource.setDefaultTargetDataSource(
			createDataSourceInstance(getDbInstanceIdentifier()));

	// Initialize the class
	dataSource.afterPropertiesSet();

	return new LazyConnectionDataSourceProxy(dataSource);
}
 
Example 26
private boolean isDatabaseAvailable(RetryContext context) {
	DescribeDBInstancesResult describeDBInstancesResult;
	try {
		describeDBInstancesResult = this.amazonRDS.describeDBInstances(
				new DescribeDBInstancesRequest().withDBInstanceIdentifier(
						(String) context.getAttribute(DB_INSTANCE_ATTRIBUTE_NAME)));
	}
	catch (DBInstanceNotFoundException e) {
		LOGGER.warn(
				"Database Instance with name {} has been removed or is not configured correctly, no retry possible",
				getDbInstanceIdentifier());
		// Database has been deleted while operating, hence we can not retry
		return false;
	}

	if (describeDBInstancesResult.getDBInstances().size() == 1) {
		DBInstance dbInstance = describeDBInstancesResult.getDBInstances().get(0);
		InstanceStatus instanceStatus = InstanceStatus
				.fromDatabaseStatus(dbInstance.getDBInstanceStatus());
		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("Status of database to be retried is {}", instanceStatus);
		}
		return instanceStatus.isRetryable();
	}
	else {
		throw new IllegalStateException(
				"Multiple databases found for same identifier, this is likely an incompatibility with the Amazon SDK");
	}
}
 
Example 27
@Test
void afterPropertiesSet_instanceWithoutReadReplica_createsNoDataSourceRouter()
		throws Exception {
	// Arrange
	AmazonRDS amazonRDS = mock(AmazonRDS.class);
	DataSourceFactory dataSourceFactory = mock(DataSourceFactory.class);

	when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest()
			.withDBInstanceIdentifier("test"))).thenReturn(
					new DescribeDBInstancesResult().withDBInstances(new DBInstance()
							.withDBInstanceStatus("available").withDBName("test")
							.withDBInstanceIdentifier("test").withEngine("mysql")
							.withMasterUsername("admin").withEndpoint(new Endpoint()
									.withAddress("localhost").withPort(3306))));

	AmazonRdsReadReplicaAwareDataSourceFactoryBean factoryBean = new AmazonRdsReadReplicaAwareDataSourceFactoryBean(
			amazonRDS, "test", "secret");
	factoryBean.setDataSourceFactory(dataSourceFactory);
	when(dataSourceFactory.createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret")))
					.thenReturn(mock(DataSource.class));

	// Act
	factoryBean.afterPropertiesSet();

	// Assert
	DataSource datasource = factoryBean.getObject();
	assertThat(datasource).isNotNull();

	verify(dataSourceFactory, times(1)).createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret"));
}
 
Example 28
@Test
void newInstance_withResourceIdResolver_createsInstanceWithResolvedName()
		throws Exception {
	// Arrange
	AmazonRDS amazonRDS = mock(AmazonRDS.class);
	DataSourceFactory dataSourceFactory = mock(DataSourceFactory.class);
	ResourceIdResolver resourceIdResolver = mock(ResourceIdResolver.class);
	DataSource dataSource = mock(DataSource.class);

	when(resourceIdResolver.resolveToPhysicalResourceId("test")).thenReturn("bar");

	when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest()
			.withDBInstanceIdentifier("bar"))).thenReturn(
					new DescribeDBInstancesResult().withDBInstances(new DBInstance()
							.withDBInstanceStatus("available").withDBName("test")
							.withDBInstanceIdentifier("bar").withEngine("mysql")
							.withMasterUsername("admin").withEndpoint(new Endpoint()
									.withAddress("localhost").withPort(3306))));

	when(dataSourceFactory.createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret")))
					.thenReturn(dataSource);

	AmazonRdsDataSourceFactoryBean amazonRdsDataSourceFactoryBean = new AmazonRdsDataSourceFactoryBean(
			amazonRDS, "test", "secret");
	amazonRdsDataSourceFactoryBean.setDataSourceFactory(dataSourceFactory);
	amazonRdsDataSourceFactoryBean.setResourceIdResolver(resourceIdResolver);

	// Act
	amazonRdsDataSourceFactoryBean.afterPropertiesSet();

	// Assert
	assertThat(amazonRdsDataSourceFactoryBean.getObject()).isNotNull();

	verify(dataSourceFactory, times(1)).createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret"));
}
 
Example 29
@Test
void afterPropertiesSet_noUserNameSet_createsInstanceWithUserNameFromMetaData()
		throws Exception {
	// Arrange
	AmazonRDS amazonRDS = mock(AmazonRDS.class);
	DataSourceFactory dataSourceFactory = mock(DataSourceFactory.class);
	DataSource dataSource = mock(DataSource.class);

	when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest()
			.withDBInstanceIdentifier("test"))).thenReturn(
					new DescribeDBInstancesResult().withDBInstances(new DBInstance()
							.withDBInstanceStatus("available").withDBName("test")
							.withDBInstanceIdentifier("test").withEngine("mysql")
							.withMasterUsername("admin").withEndpoint(new Endpoint()
									.withAddress("localhost").withPort(3306))));

	when(dataSourceFactory.createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret")))
					.thenReturn(dataSource);

	AmazonRdsDataSourceFactoryBean amazonRdsDataSourceFactoryBean = new AmazonRdsDataSourceFactoryBean(
			amazonRDS, "test", "secret");
	amazonRdsDataSourceFactoryBean.setDataSourceFactory(dataSourceFactory);

	// Act
	amazonRdsDataSourceFactoryBean.afterPropertiesSet();

	// Assert
	DataSource datasource = amazonRdsDataSourceFactoryBean.getObject();
	assertThat(datasource).isNotNull();

	verify(dataSourceFactory, times(1)).createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret"));
}
 
Example 30
@Test
void destroyInstance_shutdownInitiated_destroysDynamicDataSource() throws Exception {
	AmazonRDS amazonRDS = mock(AmazonRDS.class);
	DataSourceFactory dataSourceFactory = mock(DataSourceFactory.class);
	DataSource dataSource = mock(DataSource.class);

	when(amazonRDS.describeDBInstances(new DescribeDBInstancesRequest()
			.withDBInstanceIdentifier("test"))).thenReturn(
					new DescribeDBInstancesResult().withDBInstances(new DBInstance()
							.withDBInstanceStatus("available").withDBName("test")
							.withDBInstanceIdentifier("test").withEngine("mysql")
							.withMasterUsername("admin").withEndpoint(new Endpoint()
									.withAddress("localhost").withPort(3306))));

	when(dataSourceFactory.createDataSource(new DataSourceInformation(
			DatabaseType.MYSQL, "localhost", 3306, "test", "admin", "secret")))
					.thenReturn(dataSource);

	AmazonRdsDataSourceFactoryBean amazonRdsDataSourceFactoryBean = new AmazonRdsDataSourceFactoryBean(
			amazonRDS, "test", "secret");
	amazonRdsDataSourceFactoryBean.setDataSourceFactory(dataSourceFactory);
	amazonRdsDataSourceFactoryBean.afterPropertiesSet();

	amazonRdsDataSourceFactoryBean.getObject();

	amazonRdsDataSourceFactoryBean.destroy();

	verify(dataSourceFactory, times(1)).closeDataSource(dataSource);
}