Esempio n. 1
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonRDSConfig config = new AmazonRDSConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonRDSClient client = new AmazonRDSClient(creds, config);

            DownloadDBLogFilePortionResponse resp = new DownloadDBLogFilePortionResponse();

            do
            {
                DownloadDBLogFilePortionRequest req = new DownloadDBLogFilePortionRequest
                {
                    Marker = resp.Marker
                    ,
                    NumberOfLines = maxItems
                };

                resp = client.DownloadDBLogFilePortion(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.LogFileData)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.Marker));
        }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonRDSConfig config = new AmazonRDSConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonRDSClient client = new AmazonRDSClient(creds, config);

            DescribeReservedDBInstancesResponse resp = new DescribeReservedDBInstancesResponse();

            do
            {
                DescribeReservedDBInstancesRequest req = new DescribeReservedDBInstancesRequest
                {
                    Marker = resp.Marker
                    ,
                    MaxRecords = maxItems
                };

                resp = client.DescribeReservedDBInstances(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.ReservedDBInstances)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.Marker));
        }
Esempio n. 3
0
        public APIGatewayProxyResponse Status(APIGatewayProxyRequest request, ILambdaContext context)
        {
            // Log entries show up in CloudWatch
            context.Logger.LogLine("Starting Status Function");

            var c               = new AmazonRDSClient();
            var dbs             = new DescribeDBInstancesRequest();
            var tags            = new ListTagsForResourceRequest();
            var RDSResponseList = new List <RDSStatusResponse>();

            try
            {
                var dbresponse = Task.Run(() => c.DescribeDBInstancesAsync(dbs).Result);
                dbresponse.Result.DBInstances.ForEach(instance =>
                {
                    var listtagrequest          = new ListTagsForResourceRequest();
                    listtagrequest.ResourceName = instance.DBInstanceArn;
                    //query tags on instance
                    var tagresponse = Task.Run(() => c.ListTagsForResourceAsync(listtagrequest).Result);
                    //iterate through tags
                    tagresponse.Result.TagList.ForEach(tag =>
                    {
                        //check if tag name is keep-off
                        if (tag.Key == "keep-off")
                        {
                            //set status object for response
                            var RDSstatus             = new RDSStatusResponse();
                            RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                            RDSstatus.TagValue        = tag.Value;
                            RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                            RDSResponseList.Add(RDSstatus);
                        }
                    });
                });


                var response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(RDSResponseList),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }
                    }
                };

                return(response);
            }catch (Exception ex)
            {
                var response = new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(ex),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }, { "PracticeWeek", "Rocks!" }
                    }
                };
                return(response);
            }
        }
        public async Task <DescribeDBInstancesResponse> GetDatabases()
        {
            using (var amazonRDSClient = new AmazonRDSClient(awsCredentials, RegionEndpoint.GetBySystemName(Region)))
            {
                var response = await amazonRDSClient.DescribeDBInstancesAsync();

                return(response);
            }
        }
        public List <DBDetail> GetDBProperties()
        {
            List <AWSProfile> profile;
            List <DBDetail>   list = new List <DBDetail>();

            profile = SqlHelper.GetAWSAccounts();
            //foreach (var profile_ in profile)
            //{
            //    Amazon.Util.ProfileManager.RegisterProfile(profile_.ProfileName, profile_.Accesskey, profile_.Secretkey);
            //}

            try
            {
                foreach (var profile_ in profile)
                {
                    var regions = Amazon.RegionEndpoint.EnumerableAllRegions;
                    //Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.StoredProfileAWSCredentials(profile_.ProfileName);
                    foreach (var r in regions)
                    {
                        string region_;
                        if (r.SystemName != "us-gov-west-1" && r.SystemName != "cn-north-1")
                        {
                            region_ = r.SystemName;
                            var                         region   = RegionEndpoint.GetBySystemName(region_);
                            AmazonRDSClient             rds      = new AmazonRDSClient(profile_.Accesskey, profile_.Secretkey, region);
                            DescribeDBInstancesRequest  request  = new DescribeDBInstancesRequest();
                            DescribeDBInstancesResponse response = rds.DescribeDBInstances(request);
                            List <DBInstance>           result   = response.DBInstances;
                            foreach (var db in result)
                            {
                                DBDetail dbdetail = new DBDetail();
                                dbdetail.Name        = db.DBInstanceIdentifier;
                                dbdetail.Size        = db.AllocatedStorage.ToString() + " GB";
                                dbdetail.Status      = db.DBInstanceStatus;
                                dbdetail.Type        = db.StorageType;
                                dbdetail.Key         = db.DbiResourceId;
                                dbdetail.ServerName  = db.Engine;
                                dbdetail.accountId   = profile_.accountId;
                                dbdetail.ProfileName = profile_.ProfileName;
                                dbdetail.Region      = region_;
                                list.Add(dbdetail);
                            }
                        }
                    }
                }

                return(list);
            }
            catch (Exception e)
            {
                this.log.Error(e);
                return(null);
            }
        }
Esempio n. 6
0
        internal static void WriteRds(DateTime captureTime, string accountId, RegionEndpoint regionEndPoint)
        {
            var rdsClient           = new AmazonRDSClient(regionEndPoint);
            var rdsInstanceResponse = rdsClient.DescribeDBInstances();

            foreach (var dbInstance in rdsInstanceResponse.DBInstances)
            {
                string dbJson = JsonConvert.SerializeObject(dbInstance);
                Common.UpdateTopology(captureTime, accountId, regionEndPoint.SystemName, "rds", dbInstance.DBInstanceIdentifier, dbJson, "UPDATE");
            }
        }
Esempio n. 7
0
    public async Task SnapshotRDS(Instant snapshotTime)
    {
        using AmazonRDSClient rdsClient = new AmazonRDSClient();
        var    date       = snapshotTime.InZone(TimeExtensions.EasternTimeZone).LocalDateTime.Date;
        var    dateString = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
        var    random     = Guid.NewGuid().ToString().Substring(0, 1);
        string snapName   = "AdminSnap-" + dateString + "-" + random;

        CreateDBSnapshotRequest request = new CreateDBSnapshotRequest(snapName, _instanceName);
        await rdsClient.CreateDBSnapshotAsync(request, CancellationToken.None);
    }
Esempio n. 8
0
        public async Task SnapshotRDS(Instant snapshotTime)
        {
            using (AmazonRDSClient rdsClient = new AmazonRDSClient())
            {
                var    date       = snapshotTime.InZone(DateTimeZoneProviders.Tzdb.GetZoneOrNull("America/New_York")).LocalDateTime.Date;
                var    dateString = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
                var    random     = Guid.NewGuid().ToString().Substring(0, 1);
                string snapName   = "AdminSnap-" + dateString + "-" + random;

                CreateDBSnapshotRequest request = new CreateDBSnapshotRequest(snapName, _instanceName);
                await rdsClient.CreateDBSnapshotAsync(request, CancellationToken.None);
            }
        }
Esempio n. 9
0
        protected IAmazonRDS CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonRDSConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonRDSClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Esempio n. 10
0
        public async Task <string> TakeSnapshot()
        {
            var rdsInstance = await GetRDSInstance();

            var instanceId = rdsInstance.DBInstanceIdentifier;
            //don't wrap in using block or it will be disposed before you are done with it.
            var rdsClient = new AmazonRDSClient(
                CredentiaslManager.GetCredential(environment),
                AwsCommon.GetRetionEndpoint(region));
            var request = new CreateDBSnapshotRequest($"{environment}-{DateTime.Today.ToShortDateString()}", instanceId);
            //don't await this long running task
            var response = await rdsClient.CreateDBSnapshotAsync(request);

            return(response.DBSnapshot.DBInstanceIdentifier);
        }
Esempio n. 11
0
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            SkillResponse skillResponse = new SkillResponse();

            skillResponse.Response = new ResponseBody
            {
                ShouldEndSession = false
            };

            IOutputSpeech outputSpeech  = null;
            var           log           = context.Logger;
            var           intentRequest = input.Request as IntentRequest;

            outputSpeech = new PlainTextOutputSpeech();

            if (input.GetRequestType() == typeof(LaunchRequest))
            { // einfacher Aufruf des Skills ohne Aufgabenstellung ( Intent )
                log.LogLine("39: Launch ");

                (outputSpeech as PlainTextOutputSpeech).Text = "Ergebnis der Suche nach Datenbanken: ";
                AmazonRDSClient amazonRDSClient = new AmazonRDSClient(StaticValues.AWS_ACCESS_KEY, StaticValues.AWS_SECRET_KEY, Amazon.RegionEndpoint.EUCentral1);
                try
                {
                    DescribeDBInstancesRequest request = new DescribeDBInstancesRequest();
                    // request.DBInstanceIdentifier = "opensandbox";
                    var response = amazonRDSClient.DescribeDBInstancesAsync(request);
                    foreach (var instance in response.Result.DBInstances)
                    {
                        log.LogLine(instance.DBName);
                        (outputSpeech as PlainTextOutputSpeech).Text += instance.DBName;
                        (outputSpeech as PlainTextOutputSpeech).Text += instance.Engine + " Version: " + instance.EngineVersion;
                    }
                }
                catch (Exception e)
                {
                    log.LogLine("58:" + e.Message);
                }
            }

            skillResponse.Response.OutputSpeech = outputSpeech;
            skillResponse.Version = "1.0";
            return(skillResponse);
        }
Esempio n. 12
0
        private OperationResult EstablishClient(AddonManifest manifest, DeveloperOptions devOptions, out AmazonRDSClient client)
        {
            OperationResult result;

            bool requireCreds;
            var  manifestProps   = manifest.GetProperties().ToDictionary(x => x.Key, x => x.Value);
            var  accessKey       = manifestProps["AWSClientKey"];
            var  secretAccessKey = manifestProps["AWSSecretKey"];
            var  regionEndpoint  = manifestProps["AWSRegionEndpoint"];

            var prop =
                manifest.Properties.First(
                    p => p.Key.Equals("requireDevCredentials", StringComparison.InvariantCultureIgnoreCase));

            if (bool.TryParse(prop.Value, out requireCreds) && requireCreds)
            {
                if (!ValidateDevCreds(devOptions))
                {
                    client = null;
                    result = new OperationResult()
                    {
                        IsSuccess      = false,
                        EndUserMessage =
                            "The add on requires that developer credentials are specified but none were provided."
                    };
                    return(result);
                }

                accessKey       = devOptions.AccessKey;
                secretAccessKey = devOptions.SecretAccessKey;
            }
            AmazonRDSConfig config = new AmazonRDSConfig()
            {
                RegionEndpoint = RegionEndpoint.USEast1
            };

            client = new AmazonRDSClient(accessKey, secretAccessKey, config);
            result = new OperationResult {
                IsSuccess = true
            };
            return(result);
        }
Esempio n. 13
0
    public async Task <IReadOnlyList <DatabaseSnapshotInfo> > GetRecentSnapshots()
    {
        using AmazonRDSClient rdsClient = new AmazonRDSClient();
        DescribeDBSnapshotsRequest request = new DescribeDBSnapshotsRequest()
        {
            DBInstanceIdentifier = _instanceName
        };
        DescribeDBSnapshotsResponse snaps = await rdsClient.DescribeDBSnapshotsAsync(request, CancellationToken.None);

        var orderedSnaps  = snaps.DBSnapshots.OrderBy(x => x.PercentProgress).ThenByDescending(x => x.SnapshotCreateTime);
        var domainObjects = orderedSnaps
                            .Select(x =>
                                    new DatabaseSnapshotInfo(x.DBSnapshotIdentifier,
                                                             Instant.FromDateTimeUtc(x.SnapshotCreateTime.ToUniversalTime()),
                                                             x.PercentProgress,
                                                             x.Status))
                            .ToList();

        return(domainObjects);
    }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonRDSConfig config = new AmazonRDSConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonRDSClient client = new AmazonRDSClient(creds, config);

            ListTagsForResourceResponse resp = new ListTagsForResourceResponse();
            ListTagsForResourceRequest  req  = new ListTagsForResourceRequest
            {
            };

            resp = client.ListTagsForResource(req);
            CheckError(resp.HttpStatusCode, "200");

            foreach (var obj in resp.TagList)
            {
                AddObject(obj);
            }
        }
        public bool StopDB(string name)
        {
            try
            {
                AWSAuthDetails detail;
                string[]       id = name.Split(',');

                detail = SqlHelper.GetAWSAuth(id[0], "DB");

                //var region = RegionEndpoint.GetBySystemName(detail.Region);
                var region = RegionEndpoint.GetBySystemName(id[id.Length - 1]);
                // Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.StoredProfileAWSCredentials(detail.ProfileName);
                AmazonRDSClient        rds         = new AmazonRDSClient(detail.AccessKey, detail.SecretKey, region);
                StopDBInstanceRequest  stopRequest = new StopDBInstanceRequest();
                StopDBInstanceResponse stopResponse;
                string response = "";
                for (var i = 0; i < id.Length - 1; i++)
                {
                    var instance = id[i];
                    stopRequest.DBInstanceIdentifier = instance;
                    stopResponse = rds.StopDBInstance(stopRequest);
                    response     = stopResponse.HttpStatusCode.ToString();
                }

                if (response == "OK")
                {
                    SqlHelper.UpdateDBStatus(id, "stopping");
                    return(true);
                }

                return(false);
            }
            catch (Exception e)
            {
                this.log.Error(e);
                return(false);
            }
        }
Esempio n. 16
0
        private static RdsSource InitializeRdsSource()
        {
            var lambdaClient = new AmazonRDSClient(CredentialsReader.GetCredentials(), RegionEndpoint.EUWest1);

            return(new RdsSource(lambdaClient));
        }
Esempio n. 17
0
 public ClsRdsOperations()
 {
     _rdsClient = new AmazonRDSClient(credentials, RegionEndpoint.USEast1);
 }
Esempio n. 18
0
 public RDSHelper(string profile, string region, string color) : base(profile, region, color)
 {
     client = new AmazonRDSClient(
         CredentiaslManager.GetCredential(environment),
         AwsCommon.GetRetionEndpoint(region));
 }
Esempio n. 19
0
 public Aws_Util(AWSCredentials awsCredentials, RegionEndpoint region)
 {
     //クライアント起動
     rds_client = new AmazonRDSClient(awsCredentials, region);
 }
Esempio n. 20
0
        public APIGatewayProxyResponse KeepOff(APIGatewayProxyRequest request, ILambdaContext context)
        {
            // Log entries show up in CloudWatch
            context.Logger.LogLine("Starting KeepOff Function");

            var c               = new AmazonRDSClient();
            var dbs             = new DescribeDBInstancesRequest();
            var tags            = new ListTagsForResourceRequest();
            var RDSResponseList = new List <RDSStatusResponse>();

            try {
                var dbresponse = Task.Run(() => c.DescribeDBInstancesAsync(dbs).Result);
                dbresponse.Result.DBInstances.ForEach(instance =>
                {
                    //log arn on instance
                    //context.Logger.LogLine(instance.DBInstanceArn);
                    var listtagrequest          = new ListTagsForResourceRequest();
                    listtagrequest.ResourceName = instance.DBInstanceArn;
                    //query tags on instance
                    var tagresponse = Task.Run(() => c.ListTagsForResourceAsync(listtagrequest).Result);
                    //iterate through tags
                    tagresponse.Result.TagList.ForEach(tag =>
                    {
                        //check if tag name is keep-off
                        if (tag.Key == "keep-off")
                        {
                            //context.Logger.LogLine(instance.DBInstanceArn);
                            //check if tag value is true
                            if (tag.Value == "true")
                            {
                                //check if instance is on
                                if (instance.DBInstanceStatus == "available")
                                {
                                    //check if instance is on
                                    var RDSstatus             = new RDSStatusResponse();
                                    RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                                    RDSstatus.TagValue        = tag.Value;
                                    RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                                    RDSstatus.Note            = "Making call to turn off";
                                    RDSResponseList.Add(RDSstatus);


                                    var stopdb = new StopDBInstanceRequest();
                                    stopdb.DBInstanceIdentifier = instance.DBInstanceIdentifier;

                                    var stopresponse = Task.Run(() => c.StopDBInstanceAsync(stopdb));
                                    //Log that db is stopping
                                    context.Logger.LogLine(instance.DBInstanceArn + " has been stopped with status");
                                }
                                else
                                {
                                    var RDSstatus             = new RDSStatusResponse();
                                    RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                                    RDSstatus.TagValue        = tag.Value;
                                    RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                                    RDSstatus.Note            = "Not in available state";
                                    RDSResponseList.Add(RDSstatus);
                                }
                            }
                            else
                            {
                                var RDSstatus             = new RDSStatusResponse();
                                RDSstatus.RDSInstanceName = instance.DBInstanceIdentifier;
                                RDSstatus.TagValue        = tag.Value;
                                RDSstatus.CurrentStatus   = instance.DBInstanceStatus;
                                RDSstatus.Note            = "Has Tag but Value is not true";
                                RDSResponseList.Add(RDSstatus);
                            }
                        }
                    }

                                                       );
                });


                var response = new APIGatewayProxyResponse
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(RDSResponseList),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }, { "PracticeWeek", "Rocks!" }
                    }
                };
                return(response);
            } catch (Exception ex) {
                var response = new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body       = Newtonsoft.Json.JsonConvert.SerializeObject(ex),
                    Headers    = new Dictionary <string, string> {
                        { "Content-Type", "application/json" }, { "PracticeWeek", "Rocks!" }
                    }
                };
                return(response);
            }
        }
Esempio n. 21
0
 public RDSRefresher(string sourceRDSName, string destinationRDSName)
 {
     _sourceRdsName      = sourceRDSName;
     _destinationRdsName = destinationRDSName;
     _rdsClient          = new AmazonRDSClient();
 }