Esempio n. 1
0
        public static async Task AwaitInstanceStatus(this EC2Helper ec2,
                                                     string instanceId,
                                                     InstanceSummaryStatus summaryStatus,
                                                     int timeout_ms, int intensity       = 1500,
                                                     bool thowOnTermination              = true,
                                                     CancellationToken cancellationToken = default(CancellationToken))
        {
            var            sw     = Stopwatch.StartNew();
            InstanceStatus status = null;

            do
            {
                if (status != null)
                {
                    await Task.Delay(intensity);
                }

                status = await ec2.DescribeInstanceStatusAsync(instanceId, cancellationToken);

                if (status.Status.Status == summaryStatus.ToSummaryStatus())
                {
                    return;
                }

                if (thowOnTermination &&
                    (status.InstanceState?.Name == InstanceStateName.Stopping ||
                     status.InstanceState?.Name == InstanceStateName.Terminated))
                {
                    throw new Exception($"Failed Status Await, Instane is terminated or terminating: '{status.InstanceState.Name}'");
                }
            }while (sw.ElapsedMilliseconds < timeout_ms);

            throw new TimeoutException($"Instance {instanceId} could not reach status summary '{summaryStatus}', last status summary: '{status.Status.Status}'");
        }
Esempio n. 2
0
        public static async Task <Instance> GetInstanceByName(this EC2Helper ec2, string instanceName, bool throwIfNotFound = true, CancellationToken cancellationToken = default(CancellationToken))
        {
            instanceName = instanceName?.Trim().ToLower();

            if (instanceName.IsNullOrEmpty())
            {
                throw new ArgumentException("instanceName was not defined");
            }

            var batch = await ec2.DescribeInstancesAsync(cancellationToken : cancellationToken);

            var instance = batch.SelectMany(x => x.Instances)
                           .FirstOrDefault(x => !(x?.Tags).IsNullOrEmpty() &&
                                           x.State.Code != (int)InstanceStateCode.terminated &&
                                           x.State.Code != (int)InstanceStateCode.terminating &&
                                           x.Tags.Any(y => !(y?.Key).IsNullOrEmpty() &&
                                                      y.Key.ToLower().Trim() == "name" && y?.Value?.ToLower()?.Trim() == instanceName));

            if (throwIfNotFound && instance == null)
            {
                throw new Exception($"Instance {instanceName ?? "undefined"} was not found or is being irreversibly terminated.");
            }

            return(instance);
        }
Esempio n. 3
0
        public static async Task <Dictionary <string, string> > GetEnvironmentTags(
            string instanceId    = null,
            bool throwIfNotFound = true,
            int timeoutSeconds   = 10)
        {
            if (instanceId.IsNullOrEmpty())
            {
                instanceId = await GetEnvironmentInstanceId(timeoutSeconds : (timeoutSeconds / 2));
            }

            //Console.WriteLine($"Fetching tag's from instance {instanceId ?? "undefined"} in region {region ?? "undefined"}");
            var ec2      = new EC2Helper();
            var instance = await ec2.GetInstanceById(instanceId : instanceId, throwIfNotFound : throwIfNotFound);

            return(instance?.Tags?.ToDictionary(x => x.Key, y => y.Value));
        }
Esempio n. 4
0
        public static async Task <Instance[]> ListInstancesByName(
            this EC2Helper ec2,
            string name,
            IEnumerable <InstanceStateName> stateExclude = null,
            CancellationToken cancellationToken          = default(CancellationToken))
        {
            var batch = await ec2.DescribeInstancesAsync(instanceIds : null, filters : null, cancellationToken : cancellationToken);

            var instances = batch.SelectMany(x => x.Instances).Where(x => x != null);

            if (!stateExclude.IsNullOrEmpty())
            {
                instances = instances.Where(x => x != null && !stateExclude.Contains(x.State.Name));
            }

            return(instances.Where(x =>
                                   (x.Tags?.Any(t => t?.Key?.ToLower() == "name" && t.Value == name) ?? false) == true ||
                                   x.InstanceId == name).ToArray());
        }
Esempio n. 5
0
        public static async Task <Instance> GetInstanceById(this EC2Helper ec2, string instanceId, bool throwIfNotFound = true, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (instanceId.IsNullOrEmpty())
            {
                throw new ArgumentException("instanceId was not defined");
            }

            var batch = await ec2.DescribeInstancesAsync(instanceIds : new List <string>()
            {
                instanceId
            }, filters : null, cancellationToken : cancellationToken);

            instanceId = instanceId?.Trim().ToLower();
            var instance = batch.SelectMany(x => x.Instances).FirstOrDefault(x => x?.InstanceId == instanceId);

            if (throwIfNotFound && instance == null)
            {
                throw new Exception($"Instance {instanceId ?? "undefined"} was not found.");
            }

            return(instance);
        }
Esempio n. 6
0
        public static async Task AwaitInstanceStateCode(this EC2Helper ec2, string instanceId, InstanceStateCode instanceStateCode, int timeout_ms, int intensity = 1500, CancellationToken cancellationToken = default(CancellationToken))
        {
            var            sw     = Stopwatch.StartNew();
            InstanceStatus status = null;

            do
            {
                if (status != null)
                {
                    await Task.Delay(intensity);
                }

                status = await ec2.DescribeInstanceStatusAsync(instanceId, cancellationToken);

                if (status.InstanceState.Code == (int)instanceStateCode)
                {
                    return;
                }
            }while (sw.ElapsedMilliseconds < timeout_ms);

            throw new TimeoutException($"Instance {instanceId} could not reach state code {instanceStateCode.ToString()}, last state: {status?.InstanceState?.Code.ToEnumStringOrDefault<InstanceStateCode>($"<convertion failure of value {status?.InstanceState?.Code}>")}");
        }
Esempio n. 7
0
        /// <summary>
        /// Removes all tags then adds all tags specified in the dictionary
        /// </summary>
        public static async Task <bool> UpdateTagsAsync(this EC2Helper ec2, string instanceId, Dictionary <string, string> tags, CancellationToken cancellationToken = default(CancellationToken))
        {
            var instance = await ec2.GetInstanceById(instanceId);

            var deleteTags = await ec2.DeleteAllInstanceTags(instanceId);

            if (tags.IsNullOrEmpty())
            {
                instance = await ec2.GetInstanceById(instanceId);

                return(instance.Tags.IsNullOrEmpty());
            }

            var createTags = await ec2.CreateTagsAsync(
                resourceIds : new List <string>()
            {
                instanceId
            },
                tags : tags);

            instance = await ec2.GetInstanceById(instanceId);

            return(instance.Tags.ToDictionary(x => x.Key, y => y.Value).CollectionEquals(tags, trim: true));
        }
Esempio n. 8
0
 public static Task <DeleteTagsResponse> DeleteAllInstanceTags(this EC2Helper ec2, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
 => ec2.DeleteTagsAsync(new List <string>()
 {
     instanceId
 }, tags: null, cancellationToken: cancellationToken);
Esempio n. 9
0
        public static async Task <InstanceStateChange> TerminateInstance(this EC2Helper ec2, string instanceId, CancellationToken cancellationToken = default(CancellationToken))
        {
            var resp = await ec2.TerminateInstancesAsync(new List <string>() { instanceId }, cancellationToken : cancellationToken);

            return(resp.TerminatingInstances.FirstOrDefault(x => x.InstanceId == instanceId));
        }
Esempio n. 10
0
        public static async Task <InstanceStateChange> StartInstance(this EC2Helper ec2, string instanceId, string additionalInfo = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var resp = await ec2.StartInstancesAsync(new List <string>() { instanceId }, additionalInfo : additionalInfo, cancellationToken : cancellationToken);

            return(resp.StartingInstances.FirstOrDefault(x => x.InstanceId == instanceId));
        }
Esempio n. 11
0
        public static async Task <InstanceStateChange> StopInstance(this EC2Helper ec2, string instanceId, bool force = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            var resp = await ec2.StopInstancesAsync(new List <string>() { instanceId }, force : force, cancellationToken : cancellationToken);

            return(resp.StoppingInstances.FirstOrDefault(x => x.InstanceId == instanceId));
        }
Esempio n. 12
0
        public static async Task <Instance[]> ListInstancesByTagKey(this EC2Helper ec2, string tagKey, CancellationToken cancellationToken = default(CancellationToken))
        {
            var batch = await ec2.DescribeInstancesAsync(instanceIds : null, filters : null, cancellationToken : cancellationToken);

            return(batch.SelectMany(x => x.Instances).Where(x => (x?.Tags?.Any(t => t?.Key == tagKey) ?? false) == true).ToArray());
        }
Esempio n. 13
0
        public static async Task <Instance[]> ListInstances(this EC2Helper ec2, CancellationToken cancellationToken = default(CancellationToken))
        {
            var batch = await ec2.DescribeInstancesAsync(instanceIds : null, filters : null, cancellationToken : cancellationToken);

            return(batch.SelectMany(x => x.Instances).ToArray());
        }