@Override public void validate(String name, Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { AmazonRDSClient client = provider.getClient(); boolean isValidIdentifier = checkIdentifierFormat(name, accumulator, NAME, localizationContext); if (isValidIdentifier) { checkIdentifierUniqueness(client, name, NAME, accumulator, localizationContext); } checkMasterUserPassword(configuration, accumulator, localizationContext); checkEngine(client, configuration, accumulator, localizationContext); checkInstanceClass(configuration, accumulator, localizationContext); checkAllocatedStorage(configuration, accumulator, localizationContext); checkDBSubnetGroupName(client, configuration, accumulator, localizationContext); checkStorageEncryption(configuration, accumulator, localizationContext); }
@VisibleForTesting void checkMultiAz(AmazonRDSClient client, Configured configuration, PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) { String multiAzString = configuration.getConfigurationValue(MULTI_AZ, localizationContext); if (multiAzString != null) { boolean multiAz = Boolean.parseBoolean(multiAzString); if (multiAz) { // Illegal to set Availability Zone if creating Multi-AZ deployment. String availabilityZone = configuration.getConfigurationValue(AVAILABILITY_ZONE, localizationContext); if (availabilityZone != null) { addError(accumulator, AVAILABILITY_ZONE, localizationContext, null, AVAILABILITY_ZONE_NOT_ALLOWED_FOR_MULTI_AZ, availabilityZone); } } } }
@Bean public 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; }
@Test public void parseInternal_readReplicaSupportEnabled_configuresReadReplicaEnabledFactoryBean() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); beanDefinitionBuilder.setFactoryMethod("mock"); beanDefinitionBuilder.addConstructorArgValue(AmazonRDS.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), beanDefinitionBuilder.getBeanDefinition()); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-readReplicaEnabled.xml", getClass())); //Act BeanDefinition beanDefinition = beanFactory.getBeanDefinition("test"); //Assert assertEquals(AmazonRdsReadReplicaAwareDataSourceFactoryBean.class.getName(), beanDefinition.getBeanClassName()); }
@Bean public 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; }
/** * @inheritDoc */ @Override public void createSnapshot( String snapshotName, String instanceName, Identity identity ) { AmazonRDS rds = ActivityUtils.createClient( AmazonRDSClient.class, identity ); try { rds.describeDBSnapshots( new DescribeDBSnapshotsRequest().withDBSnapshotIdentifier( snapshotName ) ); return; } catch ( DBSnapshotNotFoundException e ) { } rds.createDBSnapshot( new CreateDBSnapshotRequest( snapshotName, instanceName ) ); }
/** * @inheritDoc */ @Override public DatabaseInstance describeInstance( String instanceName, Identity identity ) { AmazonRDS rds = ActivityUtils.createClient( AmazonRDSClient.class, identity ); DescribeDBInstancesResult results = rds.describeDBInstances( new DescribeDBInstancesRequest().withDBInstanceIdentifier( instanceName ) ); if ( results.getDBInstances().isEmpty() ) { return null; } DBInstance result = results.getDBInstances().get( 0 ); return toDatabaseInstance( result ); }
/** * @inheritDoc */ @Override public String getSnapshotStatus( String snapshotName, Identity identity ) { AmazonRDS rds = ActivityUtils.createClient( AmazonRDSClient.class, identity ); try { DescribeDBSnapshotsResult result = rds.describeDBSnapshots( new DescribeDBSnapshotsRequest().withDBSnapshotIdentifier( snapshotName ) ); return result.getDBSnapshots().get( 0 ).getStatus(); } catch ( DBSnapshotNotFoundException e ) { return null; } }
/** * Constructs an AmazonRDSClient and sets the region. */ public AmazonRDSClient makeRegionalRdsClient() { AWSCredentials credentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey); AmazonRDSClient rds = new AmazonRDSClient(credentials); rds.setRegion(awsRegion); return rds; }
/** * Tests that we can make an rds client. */ @Test public void testMakeRegionalRDSClient() { AmazonRDSClient rds = awsClientFactory.makeRegionalRdsClient(); assertEquals(ServiceAbbreviations.RDS, rds.getServiceName()); }
public HikariConfig buildAmazonPoolConfig(final AmazonRDSClient amazonRds) { final DBInstance dbInstance = getDbInstance(amazonRds, rdsInstanceId); final HikariConfig hikariConfig = getCommonConfig(); hikariConfig.setUsername(username); hikariConfig.setPassword(password); hikariConfig.setJdbcUrl("jdbc:postgresql://" + dbInstance.getEndpoint().getAddress() + ":" + dbInstance.getEndpoint().getPort() + "/" + "riistakeskus"); return hikariConfig; }
private static DBInstance getDbInstance(final AmazonRDSClient amazonRds, final String rdsInstanceId) { try { final DescribeDBInstancesRequest request = new DescribeDBInstancesRequest() .withDBInstanceIdentifier(rdsInstanceId); final DescribeDBInstancesResult response = amazonRds.describeDBInstances(request); return response.getDBInstances().get(0); } catch (DBInstanceNotFoundException e) { throw new IllegalStateException("Could not find DB instance!"); } }
@Bean(destroyMethod = "close") public DataSource dataSource( final DataSourceProperties dataSourceProperties, final AWSCredentialsProvider credentialsProvider, final RegionProvider regionProvider) { final AmazonRDSClient amazonRds = new AmazonRDSClient(credentialsProvider); amazonRds.setRegion(regionProvider.getRegion()); return new HikariDataSource(dataSourceProperties.buildAmazonPoolConfig(amazonRds)); }
@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)); } } } }
@Before public void setUp() throws Exception { 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); }
/** * Collect data for RDS. * * @param stats * current statistics object. * @param account * currently used credentials object. * @param region * currently used aws region. */ public static void scanRDS(AwsStats stats, AwsAccount account, Regions region) { LOG.debug("Scan for RDS in region " + region.getName() + " in account " + account.getAccountId()); try { AmazonRDS rds = new AmazonRDSClient(account.getCredentials()); rds.setRegion(Region.getRegion(region)); List<DBInstance> list = rds.describeDBInstances().getDBInstances(); int totalItems = list.size(); for (DBInstance dbInstance : list) { AwsResource res = new AwsResource(dbInstance.getDBName(), account.getAccountId(), AwsResourceType.RDS, region); res.addInfo("DBInstanceIdentifier", dbInstance.getDBInstanceIdentifier()); stats.add(res); } LOG.info(totalItems + " RDS instances in region " + region.getName() + " in account " + account.getAccountId()); } catch (AmazonServiceException ase) { LOG.error("Exception of RDS: " + ase.getMessage()); } }
/** * Initialize parameters. * * @throws SQLException exception */ @BeforeClass public static void beforeClass() throws SQLException { initialUrl = System.getProperty("dbFailoverUrl"); initialGaleraUrl = System.getProperty("defaultGaleraUrl"); initialReplicationUrl = System.getProperty("defaultReplicationUrl"); initialLoadbalanceUrl = System.getProperty("defaultLoadbalanceUrl"); initialAuroraUrl = System.getProperty("defaultAuroraUrl"); jobId = System.getProperty("jobId", "_0"); if (initialUrl != null) { proxyUrl = createProxies(initialUrl, HaMode.NONE); } if (initialReplicationUrl != null) { proxyReplicationUrl = createProxies(initialReplicationUrl, HaMode.REPLICATION); } if (initialLoadbalanceUrl != null) { proxyLoadbalanceUrl = createProxies(initialLoadbalanceUrl, HaMode.LOADBALANCE); } if (initialGaleraUrl != null) { proxyGaleraUrl = createProxies(initialGaleraUrl, HaMode.FAILOVER); } if (initialGaleraUrl != null) { proxySequentialUrl = createProxies(initialGaleraUrl, HaMode.SEQUENTIAL); } if (initialAuroraUrl != null) { proxyAuroraUrl = createProxies(initialAuroraUrl, HaMode.AURORA); String auroraAccessKey = System.getProperty("AURORA_ACCESS_KEY"); String auroraSecretKey = System.getProperty("AURORA_SECRET_KEY"); auroraClusterIdentifier = System.getProperty("AURORA_CLUSTER_IDENTIFIER"); if (auroraAccessKey != null && auroraSecretKey != null && auroraClusterIdentifier != null) { BasicAWSCredentials awsCreds = new BasicAWSCredentials(auroraAccessKey, auroraSecretKey); amazonRDSClient = new AmazonRDSClient(awsCreds); } } }
@Override public AmazonRDSClient getClient() { AWSCredentials credentials = new Aws().getAwsCredentials(); AmazonRDSClient rds = new AmazonRDSClient(credentials); String region = getUserProperty(AWS_REGION); String endpoint = "https://rds." + region + ".amazonaws.com"; //$NON-NLS-1$ //$NON-NLS-2$ rds.setEndpoint(endpoint); return rds; }
@Bean public 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") ) ); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("read1"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("read1"). withDBInstanceIdentifier("read1"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ) ) ); return client; }
@Test public void parseInternal_customRDsClientConfigured_createInterceptorWithCustomRdsClient() throws Exception { //Arrange ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-customRdsClient.xml", getClass()); //Act classPathXmlApplicationContext.getBean(MethodInterceptor.class); //Assert assertFalse(classPathXmlApplicationContext.containsBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()))); }
@Test public void parseInternal_minimalConfiguration_createsBeanDefinitionWithoutReadReplicas() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); beanDefinitionBuilder.setFactoryMethod("mock"); beanDefinitionBuilder.addConstructorArgValue(AmazonRDS.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), beanDefinitionBuilder.getBeanDefinition()); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-minimal.xml", getClass())); AmazonRDS client = beanFactory.getBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), AmazonRDS.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") ) ); //Act DataSource dataSource = beanFactory.getBean(DataSource.class); //Assert assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); }
@Test public void parseInternal_noCredentialsDefined_returnsClientWithDefaultCredentialsProvider() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); beanDefinitionBuilder.setFactoryMethod("mock"); beanDefinitionBuilder.addConstructorArgValue(AmazonRDS.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), beanDefinitionBuilder.getBeanDefinition()); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-noCredentials.xml", getClass())); AmazonRDS client = beanFactory.getBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), AmazonRDS.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") ) ); //Act DataSource dataSource = beanFactory.getBean(DataSource.class); //Assert assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); }
@Test public void parseInternal_userTagsDefined_createsUserTagBeanDefinition() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); beanDefinitionBuilder.setFactoryMethod("mock"); beanDefinitionBuilder.addConstructorArgValue(AmazonRDS.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), beanDefinitionBuilder.getBeanDefinition()); BeanDefinitionBuilder identityBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); identityBuilder.setFactoryMethod("mock"); identityBuilder.addConstructorArgValue(AmazonIdentityManagement.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonIdentityManagement.class.getName()), identityBuilder.getBeanDefinition()); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-userTags.xml", getClass())); AmazonRDS client = beanFactory.getBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), AmazonRDS.class); AmazonIdentityManagement amazonIdentityManagement = beanFactory.getBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonIdentityManagement.class.getName()), AmazonIdentityManagement.class); when(amazonIdentityManagement.getUser()).thenReturn(new GetUserResult().withUser(new User("/", "aemruli", "123456789012", "arn:aws:iam::1234567890:user/aemruli", new Date()))); when(client.listTagsForResource(new ListTagsForResourceRequest().withResourceName("arn:aws:rds:us-west-2:1234567890:db:test"))).thenReturn(new ListTagsForResourceResult().withTagList( new Tag().withKey("key1").withValue("value2") )); //Act Map<?, ?> dsTags = beanFactory.getBean("dsTags", Map.class); //Assert assertEquals("value2", dsTags.get("key1")); }
@Bean public 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) ) ) ); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("anotherOne"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("test"). withDBInstanceIdentifier("anotherOne"). withEngine("mysql"). withMasterUsername("admin"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ) ) ); return client; }
AWSDatabase(final Map<String, AmazonEC2Client> ec2Clients, final Map<String, AmazonRDSClient> rdsClients, final Map<String, AmazonDynamoDBClient> dynamoClients, final Map<String, AmazonSQSClient> sqsClients, final Map<String, AmazonElastiCacheClient> elasticacheClients, final AmazonIdentityManagementClient iamClient) { this(ec2Clients, rdsClients, dynamoClients, sqsClients, elasticacheClients, iamClient, null); }
public BeanstalkConnector(String login, String pass, String region) { awsCredentials = new BasicAWSCredentials(login, pass); beanstalkClient = new AWSElasticBeanstalkClient(awsCredentials); this.beanstalkEndpoint = String.format("elasticbeanstalk.%s.amazonaws.com", region); beanstalkClient.setEndpoint(beanstalkEndpoint); this.rdsEndpoint = String.format("rds.%s.amazonaws.com", region); rdsClient = new AmazonRDSClient(awsCredentials); rdsClient.setEndpoint(rdsEndpoint); this.sqsEndpoint = String.format("sqs.%s.amazonaws.com", region); sqsClient=new AmazonSQSAsyncClient(awsCredentials); sqsClient.setEndpoint(this.sqsEndpoint); }
/** * @inheritDoc */ @Override public void deleteSnapshot( String snapshotName, Identity identity ) { AmazonRDS rds = ActivityUtils.createClient( AmazonRDSClient.class, identity ); try { rds.deleteDBSnapshot( new DeleteDBSnapshotRequest( snapshotName ) ); } catch ( DBSnapshotNotFoundException e ) { } }
/** * @inheritDoc */ @Override public void terminateInstance( String instanceName, Identity identity ) { AmazonRDS rds = ActivityUtils.createClient( AmazonRDSClient.class, identity ); try { rds.deleteDBInstance( new DeleteDBInstanceRequest( instanceName ).withSkipFinalSnapshot( true ) ); } catch ( DBInstanceNotFoundException e ) { } }
public RdsClient(AmazonRDSClient awsRdsClient) { this.awsRdsClient = awsRdsClient; }
@Bean @Scope(WebApplicationContext.SCOPE_APPLICATION) public AmazonRDS rdsClient(final AWSCredentialsProvider creds, final Region region) { return region.createClient(AmazonRDSClient.class, creds, null); }
public List<DBInstance> getDatabases() { AmazonRDSClient rds = getClient(); return rds.describeDBInstances().getDBInstances(); }
@Test public void parseInternal_fullConfiguration_createsBeanDefinitionWithoutReadReplicas() throws Exception { //Arrange DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(Mockito.class); beanDefinitionBuilder.setFactoryMethod("mock"); beanDefinitionBuilder.addConstructorArgValue(AmazonRDS.class); beanFactory.registerBeanDefinition(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), beanDefinitionBuilder.getBeanDefinition()); XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-fullConfiguration.xml", getClass())); AmazonRDS client = beanFactory.getBean(AmazonWebserviceClientConfigurationUtils.getBeanName(AmazonRDSClient.class.getName()), AmazonRDS.class); when(client.describeDBInstances(new DescribeDBInstancesRequest().withDBInstanceIdentifier("test"))).thenReturn( new DescribeDBInstancesResult(). withDBInstances(new DBInstance(). withDBInstanceStatus("available"). withDBName("test"). withDBInstanceIdentifier("test"). withEngine("mysql"). withEndpoint(new Endpoint(). withAddress("localhost"). withPort(3306) ) ) ); BeanDefinition definition = beanFactory.getBeanDefinition("test"); assertEquals("test", definition.getConstructorArgumentValues().getArgumentValue(1, String.class).getValue()); assertEquals("password", definition.getConstructorArgumentValues().getArgumentValue(2, String.class).getValue()); assertEquals("myUser", definition.getPropertyValues().getPropertyValue("username").getValue()); assertEquals("fooDb", definition.getPropertyValues().getPropertyValue("databaseName").getValue()); DataSource dataSource = beanFactory.getBean(DataSource.class); //Assert assertNotNull(dataSource); assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource); }
public AWSDatabaseHolder(Config config) { maxAgeInMs = config.getDuration("maxAge", TimeUnit.MILLISECONDS); final DefaultAWSCredentialsProviderChain awsCredentialsProviderChain = new DefaultAWSCredentialsProviderChain(); final ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setRetryPolicy(new RetryPolicy(null, null, config.getInt("maxErrorRetry"), true)); final AmazonEC2Client bootstrapEC2Client = new AmazonEC2Client(awsCredentialsProviderChain); ec2Clients = Maps.newHashMap(); rdsClients = Maps.newHashMap(); sqsClients = Maps.newHashMap(); dynamoDBClients = Maps.newHashMap(); elasticacheClients = Maps.newHashMap(); final List<Region> ec2Regions = bootstrapEC2Client.describeRegions().getRegions(); for (Region region : ec2Regions) { final String regionName = region.getRegionName(); final String endpoint = region.getEndpoint(); log.debug("Adding ec2 region {}", region); final AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentialsProviderChain, clientConfig); ec2Client.setEndpoint(endpoint); ec2Clients.put(regionName, ec2Client); final AmazonRDSClient rdsClient = new AmazonRDSClient(awsCredentialsProviderChain, clientConfig); rdsClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "rds.")); rdsClients.put(regionName, rdsClient); final AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(awsCredentialsProviderChain, clientConfig); dynamoDBClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "dynamodb.")); dynamoDBClients.put(regionName, dynamoDBClient); final AmazonSQSClient sqsClient = new AmazonSQSClient(awsCredentialsProviderChain, clientConfig); sqsClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "sqs.")); sqsClients.put(regionName, sqsClient); final AmazonElastiCacheClient elastiCacheClient = new AmazonElastiCacheClient (awsCredentialsProviderChain, clientConfig); elastiCacheClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "elasticache.")); elasticacheClients.put(regionName, elastiCacheClient); } this.iamClient = new AmazonIdentityManagementClient(awsCredentialsProviderChain, clientConfig); if (config.hasPath("accountNumber")) { this.awsAccountNumber = config.getString("accountNumber"); } else { this.awsAccountNumber = null; } rebuild(); }
/** * @inheritDoc */ @Override public DatabaseInstance restoreSnapshot( String snapshotName, String instanceName, String subnetGroupName, Identity identity ) { AmazonRDS rds = ActivityUtils.createClient( AmazonRDSClient.class, identity ); try { DescribeDBInstancesResult results = rds.describeDBInstances( new DescribeDBInstancesRequest().withDBInstanceIdentifier( instanceName ) ); return toDatabaseInstance( results.getDBInstances().get( 0 ) ); } catch ( DBInstanceNotFoundException e ) { } DescribeDBSnapshotsResult result = rds.describeDBSnapshots( new DescribeDBSnapshotsRequest().withDBSnapshotIdentifier( snapshotName ) ); if ( result.getDBSnapshots().isEmpty() ) { throw new IllegalArgumentException( "Snapshot " + snapshotName + " is not found" ); } DBSnapshot snapshot = result.getDBSnapshots().get( 0 ); RestoreDBInstanceFromDBSnapshotRequest request = new RestoreDBInstanceFromDBSnapshotRequest( instanceName, snapshotName ); if ( snapshot.getVpcId() == null ) { request.setPubliclyAccessible( true ); } else { request.setDBSubnetGroupName( subnetGroupName ); } DBInstance ins = rds.restoreDBInstanceFromDBSnapshot( request ); DatabaseInstance desc = new DatabaseInstance(); desc.setAllocatedStorage( ins.getAllocatedStorage() ); desc.setAvailabilityZone( ins.getAvailabilityZone() ); desc.setInstanceId( ins.getDBInstanceIdentifier() ); desc.setInstanceType( ins.getDBInstanceClass() ); if ( ins.getEndpoint() != null ) { desc.setPublicHostName( ins.getEndpoint().getAddress() ); desc.setPort( ins.getEndpoint().getPort() ); } desc.setMasterUser( ins.getMasterUsername() ); return desc; }
/** * Returns the RDS client. * * @return the RDS client */ public AmazonRDSClient getClient() { return client; }