Example usage for com.amazonaws.services.rds.model DBInstance getDBInstanceIdentifier

List of usage examples for com.amazonaws.services.rds.model DBInstance getDBInstanceIdentifier

Introduction

In this page you can find the example usage for com.amazonaws.services.rds.model DBInstance getDBInstanceIdentifier.

Prototype


public String getDBInstanceIdentifier() 

Source Link

Document

Contains a user-supplied database identifier.

Usage

From source file:RDSManager.java

public String createRDS() {
    String endPointAddr = null;/*  w  w  w.  j a  v  a2 s. c  o m*/
    try {
        System.out.println("Creating RDS");
        CreateDBParameterGroupRequest cdpgr = new CreateDBParameterGroupRequest();
        cdpgr.setDBParameterGroupName(DB_PARAM_GROUP_NAME);
        cdpgr.setDescription(DB_PARAM_GROU_DESC);
        cdpgr.setDBParameterGroupFamily(DB_PARAM_GROUP_FAMILY);
        rds.createDBParameterGroup(cdpgr);

        Collection<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new Parameter().withParameterName("max_connections").withParameterValue("200")
                .withApplyMethod("immediate"));
        parameters.add(new Parameter().withParameterName("max_allowed_packet").withParameterValue("999999")
                .withApplyMethod("immediate"));

        rds.modifyDBParameterGroup(new ModifyDBParameterGroupRequest()
                .withDBParameterGroupName(DB_PARAM_GROUP_NAME).withParameters(parameters));

        /// create configuration of instance
        CreateDBInstanceRequest cdbir = new CreateDBInstanceRequest();
        cdbir.setEngine(RDS_ENGINE);
        cdbir.setEngineVersion(ENGINE_VERSION);
        cdbir.setLicenseModel(LICENSE_MODEL);
        cdbir.setAutoMinorVersionUpgrade(AUTO_MINOR_VERSION_UPGRADE);
        cdbir.setDBInstanceClass(DB_INSTANCE_TYPE);
        cdbir.setMultiAZ(MULTI_AZ);
        cdbir.setAllocatedStorage(ALLOCATED_STORAGE);
        cdbir.setDBInstanceIdentifier(DBInstanceIdentifier);
        cdbir.setMasterUsername(MASTER_USER_NAME);
        cdbir.setMasterUserPassword(MasterUserPassword);
        cdbir.setDBName(DB_NAME);
        cdbir.setPort(DB_PORT);
        cdbir.setBackupRetentionPeriod(BackupRetentionPeriod);
        cdbir.setPubliclyAccessible(PubliclyAccessible);
        cdbir.setDBParameterGroupName(DB_PARAM_GROUP_NAME);
        ArrayList<String> arrDbSecur = new ArrayList<String>();
        arrDbSecur.add(SECURITY_GROUP_NAME);
        cdbir.setDBSecurityGroups(arrDbSecur);

        System.out.println("Creating RDS DB Instance");
        // creating instance
        DBInstance dbi = rds.createDBInstance(cdbir);

        // wait till instance created
        boolean isWaiting = true;
        while (isWaiting) {
            Thread.sleep(30000);
            DescribeDBInstancesRequest request = new DescribeDBInstancesRequest();
            request.setDBInstanceIdentifier(dbi.getDBInstanceIdentifier());
            DescribeDBInstancesResult result = rds.describeDBInstances(request);
            List<DBInstance> d = result.getDBInstances();
            Iterator<DBInstance> i = d.iterator();

            while (i.hasNext()) {
                DBInstance d1 = i.next();
                System.out.println("RDS Status : " + d1.getDBInstanceStatus());
                if (d1.getDBInstanceStatus().equals("available")) {
                    isWaiting = false;
                    System.out.println("RDS Endpoint Address : " + d1.getEndpoint().getAddress());
                    endPointAddr = d1.getEndpoint().getAddress();
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return endPointAddr;
}

From source file:com.airbnb.billow.RDSInstance.java

public RDSInstance(DBInstance instance, DBCluster cluster, List<Tag> tagList) {
    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 {/* w  ww  .ja  v a  2s . c  o  m*/
        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());
    }
}

From source file:com.AWSManagementAntTask.dao.RDSDao.java

public AWSMATDto find() {

    List<IAWSDto> dtolist = new ArrayList<IAWSDto>();
    for (DBInstance res : rds.describeDBInstances().getDBInstances()) {
        RDSDto dto = new RDSDto();
        dto.setRegionName(this.dto.getRegionName());
        dto.setDBInstanceIdentifier(res.getDBInstanceIdentifier());
        dto.setDBName(res.getDBName());//from  w  w  w.  ja va  2  s .com
        dto.setDBInstanceStatus(res.getDBInstanceStatus());
        dto.setInstanceCreateTime(res.getInstanceCreateTime());
        dto.setEngine(res.getEngine());
        dto.setEngineVersion(res.getEngineVersion());
        dto.setLicenseModel(res.getLicenseModel());
        dto.setStorageType(res.getStorageType());
        dto.setAllocatedStorage(res.getAllocatedStorage());
        dto.setDBInstanceClass(res.getDBInstanceClass());
        dto.setMasterUsername(res.getMasterUsername());
        dtolist.add(dto);
    }
    this.dto.setRdslist(dtolist);
    return this.dto;
}

From source file:com.cloudera.director.aws.rds.RDSProvider.java

License:Apache License

/**
 * Performs a sequence of strict instance ownership checks to avoid any potential harmful
 * accidents.//  w w w  .  java2 s .c  om
 *
 * @param instance the instance
 * @param template the template from which the instance was created, or <code>null</code>
 *                 if it is unknown (such as during a delete call)
 * @return the virtual instance ID
 */
@SuppressWarnings("PMD.UnusedFormalParameter")
private String checkInstanceIsManagedByDirector(DBInstance instance, RDSInstanceTemplate template) {
    // TODO perform any desired tag validation
    return instance.getDBInstanceIdentifier();
}

From source file:com.github.blacklocus.rdsecho.AbstractEchoIntermediateStage.java

License:Open Source License

@Override
public Boolean call() throws Exception {

    // Validate state, make sure we're operating on what we expect to.

    String tagEchoManaged = echo.getTagEchoManaged();
    String tagEchoStage = echo.getTagEchoStage();

    LOG.info("Locating latest Echo managed instance (tagged with {}=true) in stage '{}' (tagged with {}={}).",
            tagEchoManaged, requisiteStage, tagEchoStage, requisiteStage);
    Optional<DBInstance> instanceOpt = echo.lastEchoInstance();
    if (!instanceOpt.isPresent()) {
        LOG.error("  Unable to locate Echo-managed instance. Is there one? Aborting.", tagEchoManaged);
        return false;
    }//from   w ww .j  a v a2 s.  co m

    DBInstance instance = instanceOpt.get();
    Optional<Tag> stageOpt = echo.instanceStage(instance.getDBInstanceIdentifier());
    if (!stageOpt.isPresent()) {
        LOG.error("Unable to read Echo stage tag so cannot determine stage. To forcefully set the stage, edit "
                + "the instance's tags to add {}={} and run this modify operation again. "
                + "Cannot continue as it is so exiting.", tagEchoStage, requisiteStage);
        return false;
    }
    String instanceStage = stageOpt.get().getValue();
    if (!requisiteStage.equals(instanceStage)) {
        LOG.error("Current Echo stage on instance is {}={} but needs to be {}={}. To forcefully set the stage, "
                + "edit the instance's tags to set the required stage and run this modify operation again. "
                + "Cannot continue as it is so exiting.", tagEchoStage, instanceStage, tagEchoStage,
                requisiteStage);
        return false;
    }

    // Looks like we found a good echo instance, but is it available to us.

    String dbInstanceId = instance.getDBInstanceIdentifier();
    LOG.info("  Located echo-managed instance with identifier {}", dbInstanceId);
    if (!"available".equals(instance.getDBInstanceStatus())) {
        LOG.error("  Instance does not have status 'available' (saw {}) so aborting.",
                instance.getDBInstanceStatus());
        return false;
    }

    // Do the part special to traversing the this stage

    if (traverseStage(instance)) {

        // Advance. This replaces, same-named tags.
        rds.addTagsToResource(new AddTagsToResourceRequest()
                .withResourceName(RdsFind.instanceArn(cfg.region(), cfg.accountNumber(),
                        instance.getDBInstanceIdentifier()))
                .withTags(new Tag().withKey(tagEchoStage).withValue(resultantStage)));

        return true;

    } else {
        return false;
    }
}

From source file:com.github.blacklocus.rdsecho.EchoModify.java

License:Open Source License

@Override
boolean traverseStage(DBInstance instance) {

    // Prepare request and build up informational message with conditional parts.

    StringWriter proposed = new StringWriter();
    PrintWriter printer = new PrintWriter(proposed);
    printer.format("Proposed db modifications...%n");

    ModifyDBInstanceRequest request = new ModifyDBInstanceRequest();
    request.withDBInstanceIdentifier(instance.getDBInstanceIdentifier());

    Optional<String> dbParameterGroupNameOpt = cfg.modDbParameterGroupName();
    if (dbParameterGroupNameOpt.isPresent()) {
        request.withDBParameterGroupName(dbParameterGroupNameOpt.get());
        printer.format("  db param group name    : %s%n", dbParameterGroupNameOpt.get());
    }/* w w  w  .  jav a  2 s . c o  m*/
    Optional<String[]> dbSecurityGroupsOpt = cfg.modDbSecurityGroups();
    if (dbSecurityGroupsOpt.isPresent()) {
        request.withDBSecurityGroups(dbSecurityGroupsOpt.get());
        printer.format("  db security groups     : %s%n", Arrays.asList(dbSecurityGroupsOpt.get()));
    }
    Optional<Integer> backupRetentionPeriodOpt = cfg.modBackupRetentionPeriod();
    if (backupRetentionPeriodOpt.isPresent()) {
        request.withBackupRetentionPeriod(backupRetentionPeriodOpt.get());
        printer.format("  backup retention period: %d%n", backupRetentionPeriodOpt.get());
    }
    boolean applyImmediately = cfg.modApplyImmediately();
    printer.format("  apply immediately      : %b%n", applyImmediately);
    request.withApplyImmediately(applyImmediately);

    LOG.info(proposed.toString());

    // Interactive user confirm

    if (cfg.interactive()) {
        String format = "Proceed to modify DB instance with these settings? Input %s to confirm.";
        String dbInstanceId = instance.getDBInstanceIdentifier();
        if (!EchoUtil.prompt(dbInstanceId, format, dbInstanceId)) {
            LOG.info("User declined to proceed. Exiting.");
            return false;
        }
    }

    // Do the deed

    LOG.info("Modifying existing DB instance.");
    rds.modifyDBInstance(request);
    LOG.info("Submitted instance modify request. The instance may need to be rebooted to receive the effect of "
            + "certain settings. See AWS RDS documentation for details:\n"
            + "http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.html#Overview.DBInstance.Modifying");

    return true;
}

From source file:com.github.blacklocus.rdsecho.EchoNew.java

License:Open Source License

@Override
public Boolean call() throws Exception {

    // Do some sanity checks to make sure we aren't generating a bunch of trouble in RDS

    String tagEchoManaged = echo.getTagEchoManaged();

    LOG.info("Checking to see if current echo-created instance (tagged {}) was created less than 24 hours ago. "
            + "If so this operation will not continue.", tagEchoManaged);
    Optional<DBInstance> newestInstanceOpt = echo.lastEchoInstance();
    if (newestInstanceOpt.isPresent()) {

        if (new DateTime(newestInstanceOpt.get().getInstanceCreateTime()).plusHours(24)
                .isAfter(DateTime.now())) {
            LOG.info("  Last echo-created RDS instance {} was created less than 24 hours ago. Aborting.",
                    tagEchoManaged);/*  w w w.jav  a 2  s  .c o  m*/
            return false;

        } else {
            LOG.info("  Last echo-created RDS instance {} was created more than 24 hours ago. Proceeding.",
                    tagEchoManaged);
        }

    } else {
        LOG.info("  No prior echo-created instance found with tag {}. Proceeding.", tagEchoManaged);
    }

    // Locate a suitable snapshot to be the basis of the new instance

    LOG.info("Locating latest snapshot from {}", cfg.snapshotDbInstanceIdentifier());
    Optional<DBSnapshot> dbSnapshotOpt = echo.latestSnapshot();
    if (dbSnapshotOpt.isPresent()) {
        DBSnapshot snapshot = dbSnapshotOpt.get();
        LOG.info("  Located snapshot {} completed on {}", snapshot.getDBSnapshotIdentifier(),
                new DateTime(snapshot.getSnapshotCreateTime()).toDateTimeISO().toString());

    } else {
        LOG.info("  Could not locate a suitable snapshot. Cannot continue.");
        return false;
    }

    // Info summary

    String dbSnapshotIdentifier = dbSnapshotOpt.get().getDBSnapshotIdentifier();
    String newDbInstanceIdentifier = cfg.name() + '-' + DateTime.now(DateTimeZone.UTC).toString("yyyy-MM-dd");
    LOG.info(
            "Proposed new db instance...\n" + "  engine           : {}\n" + "  license model    : {}\n"
                    + "  db instance class: {}\n" + "  multi az         : {}\n" + "  storage type     : {}\n"
                    + "  iops             : {}\n" + "  db snapshot id   : {}\n" + "  db instance id   : {}\n"
                    + "  port             : {}\n" + "  option group name: {}\n" + "  auto minor ver up: {}",
            cfg.newEngine(), cfg.newLicenseModel(), cfg.newDbInstanceClass(), cfg.newMultiAz(),
            cfg.newStorageType(), cfg.newIops(), dbSnapshotIdentifier, newDbInstanceIdentifier, cfg.newPort(),
            cfg.newOptionGroupName(), cfg.newAutoMinorVersionUpgrade());

    // Interactive user confirmation

    if (cfg.interactive()) {
        String format = "Proceed to create a new DB instance from this snapshot? Input %s to confirm.";
        if (!EchoUtil.prompt(newDbInstanceIdentifier, format, newDbInstanceIdentifier)) {
            LOG.info("User declined to proceed. Exiting.");
            return false;
        }
    }

    // Create the new database

    LOG.info("Creating new DB instance. Hold on to your butts.");
    RestoreDBInstanceFromDBSnapshotRequest request = new RestoreDBInstanceFromDBSnapshotRequest()
            .withEngine(cfg.newEngine()).withLicenseModel(cfg.newLicenseModel())
            .withDBInstanceClass(cfg.newDbInstanceClass()).withMultiAZ(cfg.newMultiAz())
            .withStorageType(cfg.newStorageType()).withIops(cfg.newIops())
            .withDBSnapshotIdentifier(dbSnapshotIdentifier).withDBInstanceIdentifier(newDbInstanceIdentifier)
            .withPort(cfg.newPort()).withOptionGroupName(cfg.newOptionGroupName())
            .withAutoMinorVersionUpgrade(cfg.newAutoMinorVersionUpgrade())
            .withTags(new Tag().withKey(echo.getTagEchoManaged()).withValue("true"),
                    new Tag().withKey(echo.getTagEchoStage()).withValue(EchoConst.STAGE_NEW));
    DBInstance restoredInstance = rds.restoreDBInstanceFromDBSnapshot(request);

    Optional<String[]> newTags = cfg.newTags();
    if (newTags.isPresent()) {
        List<Tag> tags = EchoUtil.parseTags(newTags.get());
        if (tags.size() > 0) {
            LOG.info("Applying tags on create new: {}", Arrays.asList(tags));
            AddTagsToResourceRequest tagsRequest = new AddTagsToResourceRequest()
                    .withResourceName(RdsFind.instanceArn(cfg.region(), cfg.accountNumber(),
                            restoredInstance.getDBInstanceIdentifier()));
            tagsRequest.setTags(tags);
            rds.addTagsToResource(tagsRequest);
        }
    }

    LOG.info("Created new DB instance. \n"
            + "  https://console.aws.amazon.com/rds/home?region={}#dbinstance:id={}\n"
            + "Additional preparation of the instance will continue once the instance becomes available.",
            cfg.region(), newDbInstanceIdentifier);

    return true;
}

From source file:com.github.blacklocus.rdsecho.EchoPromote.java

License:Open Source License

@Override
boolean traverseStage(DBInstance instance) {

    LOG.info("Reading current DNS records");
    String tld = EchoUtil.getTLD(cfg.promoteCname()) + '.';
    HostedZone hostedZone = route53Find.hostedZone(nameEquals(tld)).get();
    LOG.info("  Found corresponding HostedZone. name: {} id: {}", hostedZone.getName(), hostedZone.getId());

    ResourceRecordSet resourceRecordSet = route53Find
            .resourceRecordSet(hostedZone.getId(), cnameEquals(cfg.promoteCname())).get();
    ResourceRecord resourceRecord = getOnlyElement(resourceRecordSet.getResourceRecords());
    LOG.info("  Found CNAME {} with current value {}", resourceRecordSet.getName(), resourceRecord.getValue());

    Endpoint endpoint = instance.getEndpoint();
    String tagEchoManaged = echo.getTagEchoManaged();
    String dbInstanceId = instance.getDBInstanceIdentifier();
    if (null == endpoint) {
        LOG.info("Echo DB instance {} (id: {}) has no address. Is it still initializing?", tagEchoManaged,
                dbInstanceId);//from www.  ja v a  2s . c om
        return false;
    }
    String instanceAddr = endpoint.getAddress();
    if (resourceRecord.getValue().equals(instanceAddr)) {
        LOG.info("  Echo DB instance {} ({}) lines up with CNAME {}. Nothing to do.", tagEchoManaged,
                instanceAddr, resourceRecordSet.getName());
        return false;
    } else {
        LOG.info("  Echo DB instance {} ({}) differs from CNAME {}.", tagEchoManaged, instanceAddr,
                resourceRecordSet.getName());
    }

    if (cfg.interactive()) {
        String format = "Are you sure you want to promote %s to be the new target of %s? Input %s to confirm.";
        if (!EchoUtil.prompt(dbInstanceId, format, dbInstanceId, cfg.promoteCname(), dbInstanceId)) {
            LOG.info("User declined to proceed. Exiting.");
            return false;
        }
    }

    LOG.info("Updating CNAME {} from {} to {}", cfg.name(), resourceRecord.getValue(), instanceAddr);
    ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
            .withHostedZoneId(hostedZone.getId())
            .withChangeBatch(new ChangeBatch().withChanges(
                    new Change(ChangeAction.UPSERT, new ResourceRecordSet(cfg.promoteCname(), RRType.CNAME)
                            .withResourceRecords(new ResourceRecord(instanceAddr)).withTTL(cfg.promoteTtl()))));
    route53.changeResourceRecordSets(request);

    Optional<String[]> promoteTags = cfg.promoteTags();
    if (promoteTags.isPresent()) {
        List<Tag> tags = EchoUtil.parseTags(promoteTags.get());
        if (tags.size() > 0) {
            LOG.info("Applying tags on promote: {}", Arrays.asList(tags));
            AddTagsToResourceRequest tagsRequest = new AddTagsToResourceRequest().withResourceName(
                    RdsFind.instanceArn(cfg.region(), cfg.accountNumber(), instance.getDBInstanceIdentifier()));
            tagsRequest.setTags(tags);
            rds.addTagsToResource(tagsRequest);
        }
    }

    LOG.info("Searching for any existing promoted instance to demote.");

    return true;
}

From source file:com.github.blacklocus.rdsecho.EchoReboot.java

License:Open Source License

@Override
boolean traverseStage(DBInstance instance) {

    String dbInstanceId = instance.getDBInstanceIdentifier();
    if (cfg.interactive()) {
        if (!EchoUtil.prompt(dbInstanceId,
                "Are you sure you would like to reboot the instance? Input %s to confirm.", dbInstanceId)) {
            LOG.info("User declined to proceed. Exiting.");
            return false;
        }/*from  ww w. j a  va2  s  . co  m*/
    }

    LOG.info("Rebooting instance {}", dbInstanceId);
    rds.rebootDBInstance(new RebootDBInstanceRequest().withDBInstanceIdentifier(dbInstanceId));

    return true;
}

From source file:com.github.blacklocus.rdsecho.EchoRetire.java

License:Open Source License

@Override
boolean traverseStage(DBInstance instance) {

    String dbInstanceId = instance.getDBInstanceIdentifier();
    LOG.info("Propose to retire (destroy) instance {}", dbInstanceId);

    if (cfg.interactive()) {
        String format = "Are you sure you want to retire this instance? Input %s to confirm.";
        if (!EchoUtil.prompt(dbInstanceId, format, dbInstanceId)) {
            LOG.info("User declined to proceed. Exiting.");
            return false;
        }/*from  w  w  w .j a  va2s . com*/
    }

    LOG.info("Retiring instance {}", dbInstanceId);
    DeleteDBInstanceRequest request = new DeleteDBInstanceRequest().withDBInstanceIdentifier(dbInstanceId)
            .withSkipFinalSnapshot(cfg.retireSkipFinalSnapshot().orNull())
            .withFinalDBSnapshotIdentifier(cfg.retireFinalDbSnapshotIdentifier().orNull());
    rds.deleteDBInstance(request);
    LOG.info("So long {}", dbInstanceId);

    return true;
}