Esempio n. 1
0
        /// <summary>
        /// This function will shutdown instances that are tagged with "ShutdownAfter" and a (UTC) date/time.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task FunctionHandler(Amazon.Lambda.CloudWatchEvents.ScheduledEvents.ScheduledEvent scheduledEvent, ILambdaContext context)
        {
            // We don't actually care about the scheduled event, it's just here to trigger the function

            // Note: This only works for the first 1000 instances...
            DescribeInstancesRequest request = new DescribeInstancesRequest()
            {
                MaxResults = 1000,
                // Filter for only those instances that are tagged and are running.
                Filters = new List <Filter>
                {
                    new Filter("tag:ShutdownAfter", new List <string> {
                        "*"
                    }),
                    new Filter("instance-state-name", new List <string> {
                        "running"
                    })
                }
            };
            DescribeInstancesResponse response = await _client.DescribeInstancesAsync(request);

            context.Logger.LogLine($"Found {response.Reservations.Count} tagged instances");

            foreach (var reservation in response.Reservations)
            {
                foreach (var instance in reservation.Instances)
                {
                    await TryShutdownInstance(instance, context);
                }
            }
        }
        public static DescribeInstancesResponse Unmarshall(UnmarshallerContext context)
        {
            DescribeInstancesResponse describeInstancesResponse = new DescribeInstancesResponse();

            describeInstancesResponse.HttpResponse = context.HttpResponse;
            describeInstancesResponse.RequestId    = context.StringValue("DescribeInstances.RequestId");
            describeInstancesResponse.TotalCount   = context.LongValue("DescribeInstances.TotalCount");
            describeInstancesResponse.PageNumber   = context.IntegerValue("DescribeInstances.PageNumber");
            describeInstancesResponse.PageSize     = context.IntegerValue("DescribeInstances.PageSize");

            List <DescribeInstancesResponse.DescribeInstances_Instance> describeInstancesResponse_instances = new List <DescribeInstancesResponse.DescribeInstances_Instance>();

            for (int i = 0; i < context.Length("DescribeInstances.Instances.Length"); i++)
            {
                DescribeInstancesResponse.DescribeInstances_Instance instance = new DescribeInstancesResponse.DescribeInstances_Instance();
                instance.InstanceId         = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceId");
                instance.InstanceName       = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceName");
                instance.Status             = context.StringValue("DescribeInstances.Instances[" + i + "].Status");
                instance.PayType            = context.StringValue("DescribeInstances.Instances[" + i + "].PayType");
                instance.CreatedTime        = context.StringValue("DescribeInstances.Instances[" + i + "].CreatedTime");
                instance.ExpireTime         = context.StringValue("DescribeInstances.Instances[" + i + "].ExpireTime");
                instance.MajorVersion       = context.StringValue("DescribeInstances.Instances[" + i + "].MajorVersion");
                instance.Engine             = context.StringValue("DescribeInstances.Instances[" + i + "].Engine");
                instance.IsHa               = context.BooleanValue("DescribeInstances.Instances[" + i + "].IsHa");
                instance.NetworkType        = context.StringValue("DescribeInstances.Instances[" + i + "].NetworkType");
                instance.VpcId              = context.StringValue("DescribeInstances.Instances[" + i + "].VpcId");
                instance.VswitchId          = context.StringValue("DescribeInstances.Instances[" + i + "].VswitchId");
                instance.MasterInstanceType = context.StringValue("DescribeInstances.Instances[" + i + "].MasterInstanceType");
                instance.MasterNodeCount    = context.IntegerValue("DescribeInstances.Instances[" + i + "].MasterNodeCount");
                instance.MasterDiskType     = context.StringValue("DescribeInstances.Instances[" + i + "].MasterDiskType");
                instance.MasterDiskSize     = context.IntegerValue("DescribeInstances.Instances[" + i + "].MasterDiskSize");
                instance.CoreInstanceType   = context.StringValue("DescribeInstances.Instances[" + i + "].CoreInstanceType");
                instance.CoreNodeCount      = context.IntegerValue("DescribeInstances.Instances[" + i + "].CoreNodeCount");
                instance.CoreDiskType       = context.StringValue("DescribeInstances.Instances[" + i + "].CoreDiskType");
                instance.CoreDiskSize       = context.IntegerValue("DescribeInstances.Instances[" + i + "].CoreDiskSize");
                instance.RegionId           = context.StringValue("DescribeInstances.Instances[" + i + "].RegionId");
                instance.ZoneId             = context.StringValue("DescribeInstances.Instances[" + i + "].ZoneId");
                instance.ColdStorageStatus  = context.StringValue("DescribeInstances.Instances[" + i + "].ColdStorageStatus");
                instance.BackupStatus       = context.StringValue("DescribeInstances.Instances[" + i + "].BackupStatus");
                instance.ClusterType        = context.StringValue("DescribeInstances.Instances[" + i + "].ClusterType");
                instance.CreatedTimeUTC     = context.StringValue("DescribeInstances.Instances[" + i + "].CreatedTimeUTC");
                instance.ExpireTimeUTC      = context.StringValue("DescribeInstances.Instances[" + i + "].ExpireTimeUTC");

                List <DescribeInstancesResponse.DescribeInstances_Instance.DescribeInstances_Tag> instance_tags = new List <DescribeInstancesResponse.DescribeInstances_Instance.DescribeInstances_Tag>();
                for (int j = 0; j < context.Length("DescribeInstances.Instances[" + i + "].Tags.Length"); j++)
                {
                    DescribeInstancesResponse.DescribeInstances_Instance.DescribeInstances_Tag tag = new DescribeInstancesResponse.DescribeInstances_Instance.DescribeInstances_Tag();
                    tag.Key    = context.StringValue("DescribeInstances.Instances[" + i + "].Tags[" + j + "].Key");
                    tag._Value = context.StringValue("DescribeInstances.Instances[" + i + "].Tags[" + j + "].Value");

                    instance_tags.Add(tag);
                }
                instance.Tags = instance_tags;

                describeInstancesResponse_instances.Add(instance);
            }
            describeInstancesResponse.Instances = describeInstancesResponse_instances;

            return(describeInstancesResponse);
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            DescribeInstancesResponse response = new DescribeInstancesResponse();

            int targetDepth = 2;

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("reservationSet/item", targetDepth))
                    {
                        response.Reservations.Add(ReservationUnmarshaller.GetInstance().Unmarshall(context));

                        continue;
                    }
                    if (context.TestExpression("nextToken", targetDepth))
                    {
                        response.NextToken = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
            }


            return(response);
        }
Esempio n. 4
0
    /// <summary>
    /// Recupera as instâncias EC2 existentes.
    /// </summary>
    /// <returns>Lista de instâncias EC2</returns>
    public IList <Instance> GetInstances()
    {
        List <Instance> result = new List <Instance>();

        // Recupera as instancias.
        try
        {
            DescribeInstancesRequest  ec2Request  = new DescribeInstancesRequest();
            DescribeInstancesResponse ec2Response = Ec2.DescribeInstances(ec2Request);

            foreach (Reservation ec2Reservation in ec2Response.Reservations)
            {
                foreach (Instance ec2Instance in ec2Reservation.Instances)
                {
                    result.Add(ec2Instance);
                }
            }
        }
        catch (AmazonEC2Exception ex)
        {
            throw new AwsException(ex);
        }

        return(result);
    }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            DescribeInstancesResponse response = new DescribeInstancesResponse();

            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth = 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("nextToken", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.NextToken = unmarshaller.Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("reservationSet/item", targetDepth))
                    {
                        var unmarshaller = ReservationUnmarshaller.Instance;
                        var item         = unmarshaller.Unmarshall(context);
                        response.Reservations.Add(item);
                        continue;
                    }
                }
            }

            return(response);
        }
Esempio n. 6
0
        private static void ManageInstanceSecurityGroups()
        {
            IAmazonEC2 ec2 = new Amazon.EC2.AmazonEC2Client();
            DescribeInstancesResponse instanceResponse = ec2.DescribeInstances();

            foreach (var reservation in instanceResponse.Reservations)
            {
                foreach (var rInstance in reservation.Instances)
                {
                    var securityGroupList = new List <string>();
                    foreach (var groupIdentifier in rInstance.SecurityGroups)
                    {
                        securityGroupList.Add(groupIdentifier.GroupId);
                    }
                    if (!securityGroupList.Contains("sg-9cc4a3fb"))
                    {
                        securityGroupList.Add("sg-9cc4a3fb");
                    }
                    else
                    {
                        securityGroupList.Remove("sg-9cc4a3fb");
                    }
                    var modifyInstanceAttributeRequest = new ModifyInstanceAttributeRequest();
                    modifyInstanceAttributeRequest.InstanceId = rInstance.InstanceId;
                    modifyInstanceAttributeRequest.Groups     = securityGroupList;
                    try
                    {
                        ec2.ModifyInstanceAttribute(modifyInstanceAttributeRequest);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        private void SetUpResponse()
        {
            var response       = new DescribeInstancesResponse();
            var reservationOne = new Reservation
            {
                Instances = new List <Instance>
                {
                    GenerateInstance("one", InstanceStateName.Running),
                    GenerateInstance("two", InstanceStateName.Stopped),
                    GenerateInstance("three", InstanceStateName.Terminated)
                }
            };

            var reservationTwo = new Reservation
            {
                Instances = new List <Instance>
                {
                    GenerateInstance("four", InstanceStateName.Terminated),
                    GenerateInstance("five", InstanceStateName.Terminated),
                    GenerateInstance("six", InstanceStateName.Running),
                    GenerateInstance("seven", InstanceStateName.Stopping)
                }
            };

            response.Reservations = new List <Reservation> {
                reservationOne, reservationTwo
            };
            Ec2ClientMock.Setup(x => x.DescribeInstances()).Returns(response);
        }
Esempio n. 8
0
        private DescribeInstancesResponse GetRunningInstances()
        {
            DescribeInstancesRequest  request = new DescribeInstancesRequest();
            DescribeInstancesResponse resp    = ec2.DescribeInstances(request);

            return(resp);
        }
Esempio n. 9
0
        public static DescribeInstancesResponse Unmarshall(UnmarshallerContext _ctx)
        {
            DescribeInstancesResponse describeInstancesResponse = new DescribeInstancesResponse();

            describeInstancesResponse.HttpResponse = _ctx.HttpResponse;
            describeInstancesResponse.RequestId    = _ctx.StringValue("DescribeInstances.RequestId");
            describeInstancesResponse.TotalCount   = _ctx.LongValue("DescribeInstances.TotalCount");

            List <DescribeInstancesResponse.DescribeInstances_Instance> describeInstancesResponse_instances = new List <DescribeInstancesResponse.DescribeInstances_Instance>();

            for (int i = 0; i < _ctx.Length("DescribeInstances.Instances.Length"); i++)
            {
                DescribeInstancesResponse.DescribeInstances_Instance instance = new DescribeInstancesResponse.DescribeInstances_Instance();
                instance.InstanceId     = _ctx.StringValue("DescribeInstances.Instances[" + i + "].InstanceId");
                instance.Remark         = _ctx.StringValue("DescribeInstances.Instances[" + i + "].Remark");
                instance.Status         = _ctx.IntegerValue("DescribeInstances.Instances[" + i + "].Status");
                instance.DebtStatus     = _ctx.IntegerValue("DescribeInstances.Instances[" + i + "].DebtStatus");
                instance.ExpireTime     = _ctx.LongValue("DescribeInstances.Instances[" + i + "].ExpireTime");
                instance.CreateTime     = _ctx.LongValue("DescribeInstances.Instances[" + i + "].CreateTime");
                instance.Edition        = _ctx.IntegerValue("DescribeInstances.Instances[" + i + "].Edition");
                instance.Enabled        = _ctx.IntegerValue("DescribeInstances.Instances[" + i + "].Enabled");
                instance.ConnInstanceId = _ctx.StringValue("DescribeInstances.Instances[" + i + "].ConnInstanceId");

                describeInstancesResponse_instances.Add(instance);
            }
            describeInstancesResponse.Instances = describeInstancesResponse_instances;

            return(describeInstancesResponse);
        }
Esempio n. 10
0
        public List <InstanceRequest> validEC2Instances()
        {
            DescribeInstancesRequest  request             = new DescribeInstancesRequest();
            DescribeInstancesResponse response            = Ec2Client.DescribeInstancesAsync().GetAwaiter().GetResult();
            List <InstanceRequest>    instanceRequestList = new List <InstanceRequest>();

            foreach (Reservation item in response.Reservations)
            {
                foreach (Instance instance in item.Instances)
                {
                    Tag    nameTag        = instance.Tags.Where(x => x.Key == "Name").FirstOrDefault();
                    string nameOfInstance = nameTag != null ? nameTag.Value : instance.InstanceId;

                    instanceRequestList.Add(
                        new InstanceRequest(
                            nameOfInstance,
                            string.Empty,
                            instance.InstanceId,
                            instance.State.Name.Value
                            )
                        );
                }
            }
            return(instanceRequestList);
        }
Esempio n. 11
0
    protected void InsertButton_Click(object sender, EventArgs e)
    {
        Auth.CheckPermission("STARTAWS", "START");

        // Crea i parametri di lancio
        var myRegion  = RegionEndpoint.GetBySystemName(ConfigurationManager.AppSettings["AWS_REGION"]); // non funziona in appsettings.json...
        var ec2Client = new AmazonEC2Client(new BasicAWSCredentials(ConfigurationManager.AppSettings["AWS_ACCESSKEY"], ConfigurationManager.AppSettings["AWS_SECRETKEY"]), myRegion);
        var req       = new DescribeInstancesRequest {
            InstanceIds = { ConfigurationManager.AppSettings["AWS_INSTANCEID"] }
        };

        // Recupera lo stato dell'instanza
        DescribeInstancesResponse res = ec2Client.DescribeInstances(req);

        if (res.Reservations[0].Instances[0].State.Code != 80)
        {
            return; // non fa niente
        }

        StartInstancesRequest launchRequest = new StartInstancesRequest {
            InstanceIds = { ConfigurationManager.AppSettings["AWS_INSTANCEID"] }
        };
        StartInstancesResponse launchResponse = ec2Client.StartInstances(launchRequest);

        SetPageData(); // refresh pagina
    }
Esempio n. 12
0
        public static void InvokeListInstances()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            IAmazonEC2 ec2 = AWSClientFactory.CreateAmazonEC2Client(RegionEndpoint.USWest2);

            DescribeInstancesRequest request = new DescribeInstancesRequest();

            try
            {
                DescribeInstancesResponse ec2Response = ec2.DescribeInstances(request);
                int numInstances = 0;
                numInstances = ec2Response.Reservations.Count;
                Console.WriteLine("You have " + numInstances + " Amazon EC2 instance(s) running.");
            }
            catch (AmazonEC2Exception ex)
            {
                if (ex.ErrorCode.Equals("OptInRequired"))
                {
                    Console.WriteLine("You are not signed for Amazon EC2.");
                    Console.WriteLine("You can sign up at http://aws.amazon.com/ec2.");
                }
                else
                {
                    Console.WriteLine("Caught Exception: " + ex.Message);
                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                    Console.WriteLine("Error Type: " + ex.ErrorType);
                    Console.WriteLine("Request ID: " + ex.RequestId);
                }
            }
            Console.WriteLine();
        }
Esempio n. 13
0
        public List <Instance> GetWorkerInstances()
        {
            List <Instance> instances = new List <Instance>();

            try
            {
                DescribeInstancesResponse ec2Response = _ec2Client.DescribeInstances();
                foreach (Reservation r in ec2Response.Reservations)
                {
                    instances.AddRange(r.Instances);
                }
            }
            catch (AmazonEC2Exception ex)
            {
                if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                {
                    Console.WriteLine("The account you are using is not signed up for Amazon EC2.");
                    Console.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2");
                }
                else
                {
                    Console.WriteLine("Caught Exception: " + ex.Message);
                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                    Console.WriteLine("Error Type: " + ex.ErrorType);
                    Console.WriteLine("Request ID: " + ex.RequestId);
                }
            }

            return(instances);
        }
Esempio n. 14
0
        /// <summary>
        /// Wait for the instances to become in the desired state.
        /// </summary>
        /// <param name="instanceIds"></param>
        /// <param name="desiredState"></param>
        /// <param name="timeOutSeconds"></param>
        /// <param name="pollIntervalSeconds"></param>
        public void WaitForInstances(string[] instanceIds, string desiredState, int timeOutSeconds, int pollIntervalSeconds)
        {
            DateTime waitUntil = DateTime.Now.AddSeconds(timeOutSeconds);
            var      request   = new DescribeInstancesRequest {
                InstanceId = new List <string>(instanceIds)
            };

            do
            {
                DescribeInstancesResponse response = Client.DescribeInstances(request);

                if (response.IsSetDescribeInstancesResult())
                {
                    // Are All instances in the desired state?
                    if (response.DescribeInstancesResult.Reservation.All(
                            reservation => reservation.RunningInstance.All(runningInstnace => runningInstnace.InstanceState.Name == desiredState))
                        )
                    {
                        return;
                    }
                }

                Thread.Sleep(new TimeSpan(0, 0, pollIntervalSeconds));
            } while (DateTime.Now <= waitUntil);

            throw new TimeoutException(string.Format("Timeout waiting for EC2 Instances state change."));
        }
        public static DescribeInstancesResponse Unmarshall(UnmarshallerContext context)
        {
            DescribeInstancesResponse describeInstancesResponse = new DescribeInstancesResponse();

            describeInstancesResponse.HttpResponse = context.HttpResponse;
            describeInstancesResponse.RequestId    = context.StringValue("DescribeInstances.RequestId");

            List <DescribeInstancesResponse.Instance> instances = new List <DescribeInstancesResponse.Instance>();

            for (int i = 0; i < context.Length("DescribeInstances.Instances.Length"); i++)
            {
                DescribeInstancesResponse.Instance instance = new DescribeInstancesResponse.Instance();
                instance.InstanceId                = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceId");
                instance.InstanceType              = context.EnumValue <DescribeInstancesResponse.Instance.InstanceTypeEnum>("DescribeInstances.Instances[" + i + "].InstanceType");
                instance.PackageId                 = context.EnumValue <DescribeInstancesResponse.Instance.PackageIdEnum>("DescribeInstances.Instances[" + i + "].PackageId");
                instance.Status                    = context.EnumValue <DescribeInstancesResponse.Instance.StatusEnum>("DescribeInstances.Instances[" + i + "].Status");
                instance.InnerIpAddress            = context.StringValue("DescribeInstances.Instances[" + i + "].InnerIpAddress");
                instance.JumpserverStatus          = context.EnumValue <DescribeInstancesResponse.Instance.JumpserverStatusEnum>("DescribeInstances.Instances[" + i + "].JumpserverStatus");
                instance.JumpserverInnerIpAddress  = context.StringValue("DescribeInstances.Instances[" + i + "].JumpserverInnerIpAddress");
                instance.JumpServerPublicIpAddress = context.StringValue("DescribeInstances.Instances[" + i + "].JumpServerPublicIpAddress");

                instances.Add(instance);
            }
            describeInstancesResponse.Instances = instances;

            return(describeInstancesResponse);
        }
        public void GetInstance()
        {
            // Arrange
            const string instanceId = "eight";
            var          request    = new DescribeInstancesRequest {
                InstanceIds = new List <string> {
                    instanceId
                }
            };
            var response = new DescribeInstancesResponse
            {
                Reservations = new List <Reservation>
                {
                    new Reservation
                    {
                        Instances = new List <Instance>
                        {
                            GenerateInstance(instanceId, InstanceStateName.Running)
                        }
                    }
                }
            };

            Ec2ClientMock.Setup(x => x.DescribeInstances(It.Is <DescribeInstancesRequest>(
                                                             req => req.InstanceIds.First() == request.InstanceIds.First()
                                                             ))).Returns(response);

            // Act
            Instance instance = InstanceService.GetInstance(instanceId);

            // Assert
            instance.State.Name.Should().Be(InstanceStateName.Running);
        }
Esempio n. 17
0
        private static void ChangeInstanceTags(int changeType)
        {
            IAmazonEC2 ec2 = new Amazon.EC2.AmazonEC2Client();
            DescribeInstancesResponse instanceResponse = ec2.DescribeInstances();
            var resourceIdList = new List <string>();
            var tagsList       = new List <Tag>();

            tagsList.Add(new Tag {
                Key = "Test1-AutoAdded", Value = "ToInduceConfigChages"
            });
            tagsList.Add(new Tag {
                Key = "Test2-AutoAdded", Value = "ToInduceConfigChages"
            });
            foreach (var reservation in instanceResponse.Reservations)
            {
                foreach (var rInstance in reservation.Instances)
                {
                    resourceIdList.Add(rInstance.InstanceId);
                }
            }
            if (changeType == 0)
            {
                var createTagsRequest = new CreateTagsRequest(resourceIdList, tagsList);
                ec2.CreateTags(createTagsRequest);
            }
            else if (changeType == 1)
            {
                var deleteTagsRequest = new DeleteTagsRequest();
                deleteTagsRequest.Resources = resourceIdList;
                deleteTagsRequest.Tags      = tagsList;
                ec2.DeleteTags(deleteTagsRequest);
            }
        }
Esempio n. 18
0
        private async Task <Instance> DescribeInstanceAsync()
        {
            bool worked = false;
            DescribeInstancesResponse describeInstancesResponse = null;

            var describeInstancesRequest = new DescribeInstancesRequest()
            {
                InstanceIds = new List <string>()
                {
                    this.InstanceId
                },
            };

            while (!worked)
            {
                try
                {
                    describeInstancesResponse = await this.Client.DescribeInstancesAsync(describeInstancesRequest);

                    worked = true;
                }
                catch (AmazonEC2Exception e)
                {
                    if (e.ErrorCode != "InvalidInstanceID.NotFound")
                    {
                        throw;
                    }
                }
            }

            return(describeInstancesResponse.Reservations
                   .SelectMany(x => x.Instances)
                   .Where(x => x.InstanceId == this.InstanceId)
                   .FirstOrDefault());
        }
Esempio n. 19
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            DescribeInstancesResponse response = new DescribeInstancesResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("Instances", targetDepth))
                {
                    var unmarshaller = new ListUnmarshaller <Instance, InstanceUnmarshaller>(InstanceUnmarshaller.Instance);
                    response.Instances = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("NextToken", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    response.NextToken = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

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

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

            DescribeInstancesResponse resp = new DescribeInstancesResponse();

            do
            {
                DescribeInstancesRequest req = new DescribeInstancesRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

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

                foreach (var obj in resp.Reservations)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
Esempio n. 21
0
        public async Task <Reservation[]> DescribeInstancesAsync(List <string> instanceIds = null, Dictionary <string, List <string> > filters = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var filterList = filters?.Select(x => new Filter(x.Key, x.Value)).ToList();

            DescribeInstancesResponse response = null;
            var results = new List <Reservation>();

            while ((response = await _client.DescribeInstancesAsync(new DescribeInstancesRequest()
            {
                NextToken = response?.NextToken,
                Filters = filterList,
                InstanceIds = instanceIds
            }, cancellationToken).EnsureSuccessAsync()) != null)
            {
                if (!response.Reservations.IsNullOrEmpty())
                {
                    results.AddRange(response.Reservations);
                }

                if (response.NextToken.IsNullOrEmpty())
                {
                    break;
                }

                await Task.Delay(100);
            }

            return(results.ToArray());
        }
Esempio n. 22
0
        public static Instance GetInstance(string instanceId, string regionName, string profileName)
        {
            if (string.IsNullOrWhiteSpace(instanceId))
            {
                throw new Exception("Instance id is not specified.");
            }

            AWSCredentials creds = GetAWSCredentials(profileName);

            if (creds == null)
            {
                throw new Exception("AWS credentials are not specified");
            }

            RegionEndpoint endpoint = RegionEndpoint.GetBySystemName(regionName);

            if (endpoint.DisplayName.Contains("Unknown"))
            {
                throw new Exception("AWS region endpoint is not valid.");
            }

            List <Instance> instances = new List <Instance>();
            Instance        foundInstance;

            try
            {
                using (AmazonEC2Client client = new AmazonEC2Client(creds, endpoint))
                {
                    DescribeInstancesRequest req = new DescribeInstancesRequest
                    {
                        InstanceIds = { instanceId }
                    };
                    do
                    {
                        DescribeInstancesResponse resp = client.DescribeInstances(req);
                        if (resp != null)
                        {
                            instances.AddRange(resp.Reservations.SelectMany(reservation => reservation.Instances).Where(x => x.InstanceId == instanceId));
                            req.NextToken = resp.NextToken;
                        }
                    } while (!string.IsNullOrWhiteSpace(req.NextToken));
                }

                if (instances.Count == 1)
                {
                    foundInstance = instances[0];
                }
                else
                {
                    throw new Exception("Error finding the specified instance.");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Encountered exception while describing EC2 instances: {ex.Message}");
            }

            return(foundInstance);
        }
        public void EcsRequestTest()
        {
            DescribeInstancesRequest  request  = new DescribeInstancesRequest();
            DescribeInstancesResponse response = client.GetAcsResponse(request);

            Assert.NotNull(response);
            Assert.True(0 <= response.TotalCount);
        }
Esempio n. 24
0
        /// <summary>
        /// Fetches all of the <see cref="Reservation" />s from the configured
        /// </summary>
        /// <param name="amazonEC2">
        /// An instance of <see cref="IAmazonEC2" /> to use in communicating
        /// with the AWS API.
        /// </param>
        /// <returns>
        /// An array of <see cref="Reservation" /> instances.
        /// </returns>
        private Reservation[] GetRegionReservations(IAmazonEC2 amazonEC2)
        {
            Reservation[] toReturn = null;

            // First, list the instances for the configured account.
            DescribeInstancesRequest describeInstancesRequest =
                new DescribeInstancesRequest()
            {
                MaxResults = DescribeInstancesMaxResults
            };

            List <Reservation>        allReservations           = new List <Reservation>();
            DescribeInstancesResponse describeInstancesResponse = null;

            this.loggingProvider.Debug(
                $"Pulling back {nameof(Reservation)}(s) in blocks of " +
                $"{DescribeInstancesMaxResults}.");

            string nextTokenStr = null;

            do
            {
                this.loggingProvider.Debug(
                    $"Executing {nameof(AmazonEC2Client)}." +
                    $"{nameof(amazonEC2.DescribeInstances)}...");

                describeInstancesResponse =
                    amazonEC2.DescribeInstances(describeInstancesRequest);

                this.loggingProvider.Info(
                    $"{describeInstancesResponse.Reservations.Count()} " +
                    $"{nameof(Reservation)}(s) returned.");

                allReservations.AddRange(
                    describeInstancesResponse.Reservations);

                nextTokenStr =
                    string.IsNullOrEmpty(describeInstancesResponse.NextToken)
                            ?
                    "null! Dropping out of loop."
                            :
                    $"{describeInstancesResponse.NextToken}.";

                this.loggingProvider.Info(
                    $"Next token is: {nextTokenStr}");

                describeInstancesRequest.NextToken =
                    describeInstancesResponse.NextToken;
            }while (describeInstancesResponse.NextToken != null);

            toReturn = allReservations.ToArray();

            this.loggingProvider.Info(
                $"Returning {toReturn.Length} {nameof(Reservation)} " +
                $"instance(s).");

            return(toReturn);
        }
Esempio n. 25
0
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            DescribeInstancesResponse response = new DescribeInstancesResponse();

            context.Read();

            UnmarshallResult(context, response);
            return(response);
        }
Esempio n. 26
0
        private void Window_Load(object sender, EventArgs e)
        {
            writeLog("Window_Load", "Program start");
            instResponse = new DescribeInstancesResponse();
            this.Text    = "migAz AWS (" + Assembly.GetEntryAssembly().GetName().Version.ToString() + ")";

            cmbRegion.DataSource = Regions;
            // cmbRegion.Enabled = true;
            NewVersionAvailable(); // check if there a new version of the app
        }
        public static DescribeInstancesResponse Unmarshall(UnmarshallerContext context)
        {
            DescribeInstancesResponse describeInstancesResponse = new DescribeInstancesResponse();

            describeInstancesResponse.HttpResponse = context.HttpResponse;
            describeInstancesResponse.RequestId    = context.StringValue("DescribeInstances.RequestId");
            describeInstancesResponse.PageNumber   = context.IntegerValue("DescribeInstances.PageNumber");
            describeInstancesResponse.PageSize     = context.IntegerValue("DescribeInstances.PageSize");
            describeInstancesResponse.TotalCount   = context.IntegerValue("DescribeInstances.TotalCount");

            List <DescribeInstancesResponse.DescribeInstances_KVStoreInstance> describeInstancesResponse_instances = new List <DescribeInstancesResponse.DescribeInstances_KVStoreInstance>();

            for (int i = 0; i < context.Length("DescribeInstances.Instances.Length"); i++)
            {
                DescribeInstancesResponse.DescribeInstances_KVStoreInstance kVStoreInstance = new DescribeInstancesResponse.DescribeInstances_KVStoreInstance();
                kVStoreInstance.ReplacateId      = context.StringValue("DescribeInstances.Instances[" + i + "].ReplacateId");
                kVStoreInstance.InstanceId       = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceId");
                kVStoreInstance.InstanceName     = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceName");
                kVStoreInstance.SearchKey        = context.StringValue("DescribeInstances.Instances[" + i + "].SearchKey");
                kVStoreInstance.ConnectionDomain = context.StringValue("DescribeInstances.Instances[" + i + "].ConnectionDomain");
                kVStoreInstance.Port             = context.LongValue("DescribeInstances.Instances[" + i + "].Port");
                kVStoreInstance.UserName         = context.StringValue("DescribeInstances.Instances[" + i + "].UserName");
                kVStoreInstance.InstanceStatus   = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceStatus");
                kVStoreInstance.RegionId         = context.StringValue("DescribeInstances.Instances[" + i + "].RegionId");
                kVStoreInstance.Capacity         = context.LongValue("DescribeInstances.Instances[" + i + "].Capacity");
                kVStoreInstance.InstanceClass    = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceClass");
                kVStoreInstance.QPS                 = context.LongValue("DescribeInstances.Instances[" + i + "].QPS");
                kVStoreInstance.Bandwidth           = context.LongValue("DescribeInstances.Instances[" + i + "].Bandwidth");
                kVStoreInstance.Connections         = context.LongValue("DescribeInstances.Instances[" + i + "].Connections");
                kVStoreInstance.ZoneId              = context.StringValue("DescribeInstances.Instances[" + i + "].ZoneId");
                kVStoreInstance.Config              = context.StringValue("DescribeInstances.Instances[" + i + "].Config");
                kVStoreInstance.ChargeType          = context.StringValue("DescribeInstances.Instances[" + i + "].ChargeType");
                kVStoreInstance.NetworkType         = context.StringValue("DescribeInstances.Instances[" + i + "].NetworkType");
                kVStoreInstance.VpcId               = context.StringValue("DescribeInstances.Instances[" + i + "].VpcId");
                kVStoreInstance.VSwitchId           = context.StringValue("DescribeInstances.Instances[" + i + "].VSwitchId");
                kVStoreInstance.PrivateIp           = context.StringValue("DescribeInstances.Instances[" + i + "].PrivateIp");
                kVStoreInstance.CreateTime          = context.StringValue("DescribeInstances.Instances[" + i + "].CreateTime");
                kVStoreInstance.EndTime             = context.StringValue("DescribeInstances.Instances[" + i + "].EndTime");
                kVStoreInstance.HasRenewChangeOrder = context.StringValue("DescribeInstances.Instances[" + i + "].HasRenewChangeOrder");
                kVStoreInstance.IsRds               = context.BooleanValue("DescribeInstances.Instances[" + i + "].IsRds");
                kVStoreInstance.InstanceType        = context.StringValue("DescribeInstances.Instances[" + i + "].InstanceType");
                kVStoreInstance.ArchitectureType    = context.StringValue("DescribeInstances.Instances[" + i + "].ArchitectureType");
                kVStoreInstance.NodeType            = context.StringValue("DescribeInstances.Instances[" + i + "].NodeType");
                kVStoreInstance.PackageType         = context.StringValue("DescribeInstances.Instances[" + i + "].PackageType");
                kVStoreInstance.EngineVersion       = context.StringValue("DescribeInstances.Instances[" + i + "].EngineVersion");
                kVStoreInstance.DestroyTime         = context.StringValue("DescribeInstances.Instances[" + i + "].DestroyTime");
                kVStoreInstance.ConnectionMode      = context.StringValue("DescribeInstances.Instances[" + i + "].ConnectionMode");

                describeInstancesResponse_instances.Add(kVStoreInstance);
            }
            describeInstancesResponse.Instances = describeInstancesResponse_instances;

            return(describeInstancesResponse);
        }
Esempio n. 28
0
        // ctor
        public clsGeneralStats()
        {
            // Print the number of Amazon EC2 instances.
            IAmazonEC2 ec2 = new AmazonEC2Client();
            DescribeInstancesRequest ec2Request = new DescribeInstancesRequest();

            try
            {
                DescribeInstancesResponse ec2Response = ec2.DescribeInstances(ec2Request);
                int numInstances = 0;
                numInstances = ec2Response.Reservations.Count;
                logger       = LogManager.GetLogger("thisapp");
                logger.Trace("You have {0} Amazon EC2 instance(s) running in the {1} region.",
                             numInstances, ConfigurationManager.AppSettings["AWSRegion"]);
            }
            catch (AmazonEC2Exception ex)
            {
                if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
                {
                    logger.Error("ERROR: AWS credentials invalid");
                }
                else
                {
                    logger.Error("ERROR: An error occurred with the message '{0}', response status code {1}, error code {2}, error type {3}, and request ID {4}",
                                 ex.Message, ex.StatusCode, ex.ErrorCode, ex.ErrorType, ex.RequestId);
                }
            }

            //// add refs above to Amazon.SimpleDB
            //// Print the number of Amazon SimpleDB domains.
            //IAmazonSimpleDB sdb = new AmazonSimpleDBClient();
            //ListDomainsRequest sdbRequest = new ListDomainsRequest();

            //try
            //{
            //    ListDomainsResponse sdbResponse = sdb.ListDomains(sdbRequest);

            //    int numDomains = 0;
            //    numDomains = sdbResponse.DomainNames.Count;
            //    logger.Trace("You have {0} Amazon SimpleDB domain(s) in the {1} region.", numDomains, ConfigurationManager.AppSettings["AWSRegion"]);
            //}
            //catch (AmazonSimpleDBException ex)
            //{
            //    if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure"))
            //    {
            //        logger.Error("ERROR: AWS credentials invalid");
            //    }
            //    else
            //    {
            //        logger.Error("ERROR: An error occurred with the message '{0}', response status code {1}, error code {2}, error type {3}, and request ID {4}",
            //            ex.Message, ex.StatusCode, ex.ErrorCode, ex.ErrorType, ex.RequestId);
            //    }
            //}
        }
Esempio n. 29
0
        public void BasicRpcStsTokenConnectionsTest()
        {
            BasicSessionCredentials basciCredential = new BasicSessionCredentials(this.GetBasicAccessKeyId(), this.GetBasicAccessKeySecret(), this.GetToken());
            DefaultProfile          profile         = DefaultProfile.GetProfile(this.regionId, this.GetBasicAccessKeyId(), this.GetBasicAccessKeySecret());
            DefaultAcsClient        client          = new DefaultAcsClient(profile, basciCredential);

            DescribeInstancesRequest  request  = new DescribeInstancesRequest();
            DescribeInstancesResponse response = client.GetAcsResponse(request);

            Assert.NotNull(response);
            Assert.True(0 <= response.TotalCount);
        }
Esempio n. 30
0
        public async Task <List <EC2Instance> > DescribeInstances()
        {
            List <EC2Instance> ec2Instances = new List <EC2Instance>();


            bool done        = false;
            var  instanceIds = new List <string>();
            DescribeInstancesRequest request = new DescribeInstancesRequest();

            while (!done)
            {
                DescribeInstancesResponse response = await _ec2Client.DescribeInstancesAsync(request);

                foreach (Reservation reservation in response.Reservations)
                {
                    foreach (Instance instance in reservation.Instances)
                    {
                        string ownerTag         = "";
                        string usageDescription = "";
                        string instanceName     = "";
                        foreach (var tag in instance.Tags)
                        {
                            switch (tag.Key)
                            {
                            case "owner":
                                ownerTag = tag.Value;
                                break;

                            case "usage-description":
                                usageDescription = tag.Value;
                                break;

                            case "Name":
                                instanceName = tag.Value;
                                break;
                            }
                        }

                        ec2Instances.Add(new EC2Instance(instance.InstanceId, instanceName,
                                                         instance.PublicIpAddress, instance.PublicDnsName, instance.State.Name,
                                                         instance.InstanceType, instance.ImageId, ownerTag, usageDescription));
                    }
                }

                if (response.NextToken == null)
                {
                    done = true;
                }
            }

            return(ec2Instances.OrderBy(t => t.Owner).ToList());
        }