Container for the parameters to the DescribeVolumes operation. Describes the specified EBS volumes.

If you are describing a long list of volumes, you can paginate the output to make the list more manageable. The MaxResults parameter sets the maximum number of results returned in a single page. If the list of results exceeds your MaxResults value, then that number of results is returned along with a NextToken value that can be passed to a subsequent DescribeVolumes request to retrieve the remaining results.

For more information about EBS volumes, see Amazon EBS Volumes in the Amazon Elastic Compute Cloud User Guide.

Inheritance: AmazonEC2Request
Exemplo n.º 1
0
        public static IList<VolumeRecord> GetAllVolumes(bool force = false)
        {
            if (m_Volumes == null || force)
            {
                var ec2 = Ec2ConnectionProvider.GetEc2Connection();

                DescribeVolumesRequest request = new DescribeVolumesRequest();
                DescribeVolumesResponse res = ec2.DescribeVolumes(request);

                m_Volumes = new List<VolumeRecord>();

                res.DescribeVolumesResult.Volumes.ForEach(
                        volume => m_Volumes.Add(new VolumeRecord()
                        {
                            Capacity = volume.Size,
                            Created = volume.CreateTime,
                            Id = volume.VolumeId,
                            Name = AwsTags.GetValueFromEc2Tag(volume.Tags, "Name"),
                            Status = volume.State,
                            AttachedEc2 = AttachmentToMachineNames(volume.Attachments)
                        }

                            ));

            }

            return m_Volumes;
        }
 protected override void ProcessRecord()
 {
     AmazonEC2 client = base.GetClient();
     Amazon.EC2.Model.DescribeVolumesRequest request = new Amazon.EC2.Model.DescribeVolumesRequest();
     if (string.IsNullOrEmpty(this._VolumeId))
     {
         request.VolumeId.Add(this._VolumeId);
     }
     Amazon.EC2.Model.DescribeVolumesResponse response = client.DescribeVolumes(request);
     base.WriteObject(response.DescribeVolumesResult.Volume, true);
 }
Exemplo n.º 3
0
 /// <summary>
 /// Initiates the asynchronous execution of the DescribeVolumes operation.
 /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeVolumes"/>
 /// </summary>
 /// 
 /// <param name="describeVolumesRequest">Container for the necessary parameters to execute the DescribeVolumes operation on AmazonEC2.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeVolumes
 ///         operation.</returns>
 public IAsyncResult BeginDescribeVolumes(DescribeVolumesRequest describeVolumesRequest, AsyncCallback callback, object state)
 {
     return invokeDescribeVolumes(describeVolumesRequest, callback, state, false);
 }
Exemplo n.º 4
0
 /// <summary>
 /// <para>Describes the specified Amazon EBS volumes.</para> <para>For more information about Amazon EBS volumes, see <a
 /// href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html" >Amazon EBS Volumes</a> in the <i>Amazon Elastic Compute Cloud
 /// User Guide</i> .</para>
 /// </summary>
 /// 
 /// <param name="describeVolumesRequest">Container for the necessary parameters to execute the DescribeVolumes service method on
 ///          AmazonEC2.</param>
 /// 
 /// <returns>The response from the DescribeVolumes service method, as returned by AmazonEC2.</returns>
 /// 
 public DescribeVolumesResponse DescribeVolumes(DescribeVolumesRequest describeVolumesRequest)
 {
     IAsyncResult asyncResult = invokeDescribeVolumes(describeVolumesRequest, null, null, true);
     return EndDescribeVolumes(asyncResult);
 }
Exemplo n.º 5
0
        private async Task UntilVolumeStateAsync(string volumeId, string state, CancellationToken? cancellationToken = null)
        {
            CancellationToken token = cancellationToken.HasValue ? cancellationToken.Value : new CancellationToken();

            var describeVolumesRequest = new DescribeVolumesRequest()
            {
                VolumeIds = new List<string>() { volumeId },
            };

            while (true)
            {
                token.ThrowIfCancellationRequested();

                var describeVolumesResponse = await this.Client.DescribeVolumesAsync(describeVolumesRequest);
                var status = describeVolumesResponse.Volumes.FirstOrDefault(x => x.VolumeId == volumeId).State;

                if (status == state)
                    break;
                else
                    await Task.Delay(1000, token);
            }
        }
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeVolumes operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeVolumes operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<DescribeVolumesResponse> DescribeVolumesAsync(DescribeVolumesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeVolumesRequestMarshaller();
            var unmarshaller = DescribeVolumesResponseUnmarshaller.Instance;

            return InvokeAsync<DescribeVolumesRequest,DescribeVolumesResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
Exemplo n.º 7
0
        public DescribeVolumesResult GetVolumes(Ec2Key ec2Key)
        {
            _logger.Debug("GetVolumes Start.");

            AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);

            var ec2Request = new DescribeVolumesRequest();

            DescribeVolumesResponse describeVolumesResponse = ec2.DescribeVolumes(ec2Request);

            DescribeVolumesResult result = describeVolumesResponse.DescribeVolumesResult;

            _logger.Debug("GetVolumes End.");

            return result;
        }
Exemplo n.º 8
0
 private Amazon.EC2.Model.DescribeVolumesResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.DescribeVolumesRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "DescribeVolumes");
     try
     {
         #if DESKTOP
         return(client.DescribeVolumes(request));
         #elif CORECLR
         return(client.DescribeVolumesAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
Exemplo n.º 9
0
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;

            #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
            var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
            #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute

            // create request and set iteration invariants
            var request = new Amazon.EC2.Model.DescribeVolumesRequest();

            if (cmdletContext.Filter != null)
            {
                request.Filters = cmdletContext.Filter;
            }
            if (cmdletContext.MaxResult != null)
            {
                request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value);
            }
            if (cmdletContext.VolumeId != null)
            {
                request.VolumeIds = cmdletContext.VolumeId;
            }

            // Initialize loop variant and commence piping
            var _nextToken             = cmdletContext.NextToken;
            var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));

            var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
            do
            {
                request.NextToken = _nextToken;

                CmdletOutput output;

                try
                {
                    var response = CallAWSServiceOperation(client, request);

                    object pipelineOutput = null;
                    if (!useParameterSelect)
                    {
                        pipelineOutput = cmdletContext.Select(response, this);
                    }
                    output = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };

                    _nextToken = response.NextToken;
                }
                catch (Exception e)
                {
                    output = new CmdletOutput {
                        ErrorResponse = e
                    };
                }

                ProcessOutput(output);
            } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken));

            if (useParameterSelect)
            {
                WriteObject(cmdletContext.Select(null, this));
            }


            return(null);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Describes the status of the indicated or, in lieu of any specified,  all volumes belonging to the caller. Volumes that have been deleted are not described.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeVolumesRequest request</param>
        public static void InvokeDescribeVolumes(AmazonEC2 service, DescribeVolumesRequest request)
        {
            try 
            {
                DescribeVolumesResponse response = service.DescribeVolumes(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeVolumesResponse");
                if (response.IsSetDescribeVolumesResult())
                {
                    Console.WriteLine("            DescribeVolumesResult");
                    DescribeVolumesResult  describeVolumesResult = response.DescribeVolumesResult;
                    List<Volume> volumeList = describeVolumesResult.Volume;
                    foreach (Volume volume in volumeList)
                    {
                        Console.WriteLine("                Volume");
                        if (volume.IsSetVolumeId())
                        {
                            Console.WriteLine("                    VolumeId");
                            Console.WriteLine("                        {0}", volume.VolumeId);
                        }
                        if (volume.IsSetSize())
                        {
                            Console.WriteLine("                    Size");
                            Console.WriteLine("                        {0}", volume.Size);
                        }
                        if (volume.IsSetSnapshotId())
                        {
                            Console.WriteLine("                    SnapshotId");
                            Console.WriteLine("                        {0}", volume.SnapshotId);
                        }
                        if (volume.IsSetAvailabilityZone())
                        {
                            Console.WriteLine("                    AvailabilityZone");
                            Console.WriteLine("                        {0}", volume.AvailabilityZone);
                        }
                        if (volume.IsSetStatus())
                        {
                            Console.WriteLine("                    Status");
                            Console.WriteLine("                        {0}", volume.Status);
                        }
                        if (volume.IsSetCreateTime())
                        {
                            Console.WriteLine("                    CreateTime");
                            Console.WriteLine("                        {0}", volume.CreateTime);
                        }
                        List<Attachment> attachmentList = volume.Attachment;
                        foreach (Attachment attachment in attachmentList)
                        {
                            Console.WriteLine("                    Attachment");
                            if (attachment.IsSetVolumeId())
                            {
                                Console.WriteLine("                        VolumeId");
                                Console.WriteLine("                            {0}", attachment.VolumeId);
                            }
                            if (attachment.IsSetInstanceId())
                            {
                                Console.WriteLine("                        InstanceId");
                                Console.WriteLine("                            {0}", attachment.InstanceId);
                            }
                            if (attachment.IsSetDevice())
                            {
                                Console.WriteLine("                        Device");
                                Console.WriteLine("                            {0}", attachment.Device);
                            }
                            if (attachment.IsSetStatus())
                            {
                                Console.WriteLine("                        Status");
                                Console.WriteLine("                            {0}", attachment.Status);
                            }
                            if (attachment.IsSetAttachTime())
                            {
                                Console.WriteLine("                        AttachTime");
                                Console.WriteLine("                            {0}", attachment.AttachTime);
                            }
                        }
                    }
                }
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }

            } 
            catch (AmazonEC2Exception ex) 
            {
                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("XML: " + ex.XML);
            }
        }
Exemplo n.º 11
0
        public DataTable GetEBSDetails(string aprofile, string Region2Scan)
        {
            DataTable ToReturn = AWSTables.GetEBSDetailsTable();

            string accountid = GetAccountID(aprofile);

            RegionEndpoint Endpoint2scan = RegionEndpoint.USEast1;
            //Convert the Region2Scan to an AWS Endpoint.
            foreach (var aregion in RegionEndpoint.EnumerableAllRegions)
            {
                if (aregion.DisplayName.Equals(Region2Scan))
                {
                    Endpoint2scan = aregion;
                    continue;
                }
            }
            Amazon.Runtime.AWSCredentials credential;

            try
            {
                credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
                var ec2 = new Amazon.EC2.AmazonEC2Client(credential, Endpoint2scan);

                // Describe volumes has a max limit,  so we have to make sure we collect all the data we need.
                DescribeVolumesRequest requesty = new DescribeVolumesRequest();
                requesty.MaxResults = 1000;

                var volres = ec2.DescribeVolumes();
                var volyumes = volres.Volumes;
                List<Volume> vollist = new List<Volume>();

                while (volres.NextToken != null)
                {
                    foreach (var av in volyumes)
                    {
                        try { vollist.Add(av); }
                        catch (Exception ex)
                        {
                            WriteToEventLog("EBS on " + aprofile + "/" + Region2Scan + " failed:\n" + ex.Message,EventLogEntryType.Error);
                        }
                    }
                    requesty.NextToken = volres.NextToken;
                    volres = ec2.DescribeVolumes(requesty);
                }

                foreach (var av in volyumes) vollist.Add(av);

                foreach (var onevol in vollist)
                {
                    var arow = ToReturn.NewRow();
                    arow["AccountID"] = accountid;
                    arow["Profile"] = aprofile;
                    arow["Region"] = Region2Scan;

                    arow["AZ"] = onevol.AvailabilityZone;
                    arow["CreateTime"] = onevol.CreateTime.ToString();
                    arow["Encrypted"] = onevol.Encrypted.ToString();
                    arow["IOPS"] = onevol.Iops;
                    arow["KMSKeyID"] = onevol.KmsKeyId;
                    arow["Size-G"] = onevol.Size;
                    arow["SnapshotID"] = onevol.SnapshotId;
                    arow["State"] = onevol.State.Value;

                    arow["VolumeID"] = onevol.VolumeId;
                    arow["VolumeType"] = onevol.VolumeType.Value;

                    //**********  Some extra handling required**************///
                    List<string> taglist = new List<string>();
                    foreach (var atag in onevol.Tags)
                    {
                        taglist.Add(atag.Key + ": " + atag.Value);
                    }
                    arow["Tags"] = List2String(taglist);

                    var atachs = onevol.Attachments;
                    arow["Attachments"] = onevol.Attachments.Count.ToString();
                    if (onevol.Attachments.Count > 0)
                    {
                        arow["AttachTime"] = atachs[0].AttachTime;
                        arow["DeleteonTerm"] = atachs[0].DeleteOnTermination;
                        arow["Device"] = atachs[0].Device;
                        arow["InstanceID"] = atachs[0].InstanceId;
                        arow["AttachState"] = atachs[0].State;
                    }

                    ToReturn.Rows.Add(arow);

                }

            }
            catch (Exception ex)
            {
                WriteToEventLog("EBS on " + aprofile + " failed:\n" + ex.Message, EventLogEntryType.Error);
            }




            return ToReturn;

        }
Exemplo n.º 12
0
        /// <summary>
        /// List all volumes found in region
        /// </summary>
        public static void ListVolumes()
        {
            var ec2 = Ec2Helper.CreateClient();

            DescribeVolumesRequest rq = new DescribeVolumesRequest();
            DescribeVolumesResponse rs = ec2.DescribeVolumes(rq);

            foreach (Volume v in rs.Volumes) {
                Console.WriteLine(v.VolumeId);

                DescribeTagsRequest trq = new DescribeTagsRequest();
                trq.Filters.Add(new Filter() { Name = "resource-id", Values = new List<string>() { v.VolumeId } });
                DescribeTagsResponse trs = ec2.DescribeTags(trq);
                foreach (TagDescription t in trs.Tags)
                {
                    Console.WriteLine("  " + t.Key + "=" + t.Value);

                }

            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Check for any volumes that have a snapshot scheduled based on the schedule in the snapshotSchedule tag key.
        /// </summary>
        public static void CheckForScheduledSnapshots()
        {
            Console.WriteLine("Checking for scheduled snapshots in " + Program.options.Region + "...");

            AmazonEC2Client ec2 = Ec2Helper.CreateClient();

            DescribeVolumesRequest rq = new DescribeVolumesRequest();
            rq.Filters.Add(new Filter() { Name = "tag-key", Values = new List<string>() { "snapshotSchedule" } });
            DescribeVolumesResponse rs = ec2.DescribeVolumes(rq);

            foreach (Volume v in rs.Volumes)
            {

                string[] sch2 = Ec2Helper.GetTagValue(v.Tags, "snapshotSchedule").Split(' ');

                string volumename = Ec2Helper.GetTagValue(v.Tags, "Name");

                DateTime lastSnap; // date of last snapshot
                DateTime nextSnap; // the next backup that should have occured based on last backup
                DateTime nextNextSnap; // the next backup that should occur assuming a backup runs now or ran at the last proper time

                DateTime now = DateTime.UtcNow;

                if (!DateTime.TryParse(Ec2Helper.GetTagValue(v.Tags, "lastSnapshot"), out lastSnap))
                    lastSnap = Convert.ToDateTime("1/1/2010");

                Console.WriteLine("Checking " + v.VolumeId + " / " + volumename + "...");
            //sch2 = ("hourly 4 :30 x30days").Split(' ');
            //lastSnap = Convert.ToDateTime("2/29/2012 6:00:15pm");
            //now = Convert.ToDateTime("2/29/2012 10:00:14pm");

                switch(sch2[0])
                {
                    case "hourly": // hourly, hourly 1 :15, hourly :30, hourly 4 (pass it hours between backups & when on the hour to do it, any order; defaults to every hour on the hour)

                        int ah = GetAfterTheHour(sch2, 0);
                        int hi = GetInt(sch2, 1);

                        nextSnap = lastSnap.AddMinutes(-lastSnap.Minute).AddSeconds(-lastSnap.Second).AddMilliseconds(-lastSnap.Millisecond);
                        nextSnap = nextSnap.AddHours(hi).AddMinutes(ah);

                        // this is not right
                        nextNextSnap = now.AddMinutes(-now.Minute).AddSeconds(-now.Second).AddMilliseconds(-now.Millisecond);
                        nextNextSnap = nextNextSnap.AddMinutes(ah).AddHours(hi);

                        break;

                    case "daily": // daily, 3pm, daily 15:15, daily 3:30pm (times are UTC; defaults to midnight UTC)

                        DateTime hour = GetTime(sch2, Convert.ToDateTime("0:00"));

                        nextSnap = lastSnap.Date.AddDays(1).AddTicks(hour.TimeOfDay.Ticks);

                        nextNextSnap = now.Date.AddDays(1).AddTicks(hour.TimeOfDay.Ticks);

                        break;

                    case "weekly": // weekly, weekly sunday, weekly thursday 3pm (times are UTC; defaults to sunday midnight UTC)

                        DateTime whour = GetTime(sch2, Convert.ToDateTime("0:00"));
                        DayOfWeek dow = GetDow(sch2, DayOfWeek.Sunday);

                        if(lastSnap.DayOfWeek>=dow)
                            nextSnap = lastSnap.Date.AddDays(-(int)lastSnap.DayOfWeek).AddDays(7 + (int)dow).AddTicks(whour.TimeOfDay.Ticks);
                        else
                            nextSnap = lastSnap.Date.AddDays(-(int)lastSnap.DayOfWeek).AddDays((int)dow).AddTicks(whour.TimeOfDay.Ticks);

                        nextNextSnap = now.Date.AddDays(-(int)now.DayOfWeek).AddDays(7 + (int)dow).AddTicks(whour.TimeOfDay.Ticks);
                        if (nextSnap == nextNextSnap)
                            nextNextSnap = nextNextSnap.AddDays(7);

                        break;
                    default:
                        lastSnap = now.AddYears(1);
                        nextSnap = lastSnap;
                        nextNextSnap = lastSnap;
                        break;
                }

            //Console.WriteLine("last=" + lastSnap.ToString());
            //Console.WriteLine("now=" + now);
            //Console.WriteLine("next=" + nextSnap.ToString());
            //Console.WriteLine("nextNext=" + nextNextSnap.ToString());
            //Console.ReadKey();
            //return;
                if (nextSnap <= now)
                {

                    // create snapshot of volume

                    string expires = "";
                    int expireHours = GetExpireHours(sch2, 0);
                    if (expireHours > 0)
                    {
                        expires = now.AddHours(expireHours).ToString();
                    }

                    Backup(volumename, "automatic", v.VolumeId, volumename, Ec2Helper.GetInstanceName(v.Attachments.First().InstanceId), expires);

                    // update volume tags

                    CreateTagsRequest rqq = new CreateTagsRequest();

                    rqq.Resources.Add(v.VolumeId);

                    nextSnap = nextSnap.AddSeconds(-nextSnap.Second).AddMilliseconds(-nextSnap.Millisecond);

                    rqq.Tags.Add(new Tag { Key = "lastSnapshot", Value = now.ToString() });
                    rqq.Tags.Add(new Tag { Key = "nextSnapshot", Value = nextNextSnap.ToString() });

                    var createTagResponse = ec2.CreateTags(rqq);
                }
                else
                {
                    Console.WriteLine("    Next scheduled " + nextSnap.ToString());
                }

            }
        }
Exemplo n.º 14
0
        private async Task UntilVolumeAttachedStateAsync(string state, bool allowNone = true, CancellationToken? cancellationToken = null)
        {
            CancellationToken token = cancellationToken.HasValue ? cancellationToken.Value : new CancellationToken();

            var describeVolumesRequest = new DescribeVolumesRequest()
            {
                VolumeIds = new List<string>() { this.VolumeId },
            };

            while (true)
            {
                token.ThrowIfCancellationRequested();
                var describeVolumesResponse = await this.Client.DescribeVolumesAsync(describeVolumesRequest);
                var volume = describeVolumesResponse.Volumes
                    .FirstOrDefault(x => x.VolumeId == this.VolumeId);

                if (volume != null && ((volume.Attachments.Count == 0 && allowNone) || volume.Attachments.FirstOrDefault(x => x.InstanceId == this.Instance.InstanceId).State == state))
                    break;
                else
                    await Task.Delay(1000, token);
            }
        }
Exemplo n.º 15
0
 IAsyncResult invokeDescribeVolumes(DescribeVolumesRequest describeVolumesRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new DescribeVolumesRequestMarshaller().Marshall(describeVolumesRequest);
     var unmarshaller = DescribeVolumesResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
Exemplo n.º 16
0
 /// <summary>
 /// Paginator for DescribeVolumes operation
 ///</summary>
 public IDescribeVolumesPaginator DescribeVolumes(DescribeVolumesRequest request)
 {
     return(new DescribeVolumesPaginator(this.client, request));
 }
Exemplo n.º 17
0
        /// <summary>
        /// <para> Describes the status of the indicated volume or, in lieu of any specified, all volumes belonging to the caller. Volumes that have
        /// been deleted are not described. </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeVolumes service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeVolumes service method, as returned by AmazonEC2.</returns>
		public DescribeVolumesResponse DescribeVolumes(DescribeVolumesRequest request)
        {
            var task = DescribeVolumesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
Exemplo n.º 18
0
        public object Execute(ExecutorContext context)
        {
            var cmdletContext      = context as CmdletContext;
            var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;

            // create request and set iteration invariants
            var request = new Amazon.EC2.Model.DescribeVolumesRequest();

            if (cmdletContext.Filter != null)
            {
                request.Filters = cmdletContext.Filter;
            }
            if (cmdletContext.VolumeId != null)
            {
                request.VolumeIds = cmdletContext.VolumeId;
            }

            // Initialize loop variants and commence piping
            System.String _nextToken      = null;
            int?          _emitLimit      = null;
            int           _retrievedSoFar = 0;

            if (AutoIterationHelpers.HasValue(cmdletContext.NextToken))
            {
                _nextToken = cmdletContext.NextToken;
            }
            if (AutoIterationHelpers.HasValue(cmdletContext.MaxResult))
            {
                // The service has a maximum page size of 500. If the user has
                // asked for more items than page max, and there is no page size
                // configured, we rely on the service ignoring the set maximum
                // and giving us 500 items back. If a page size is set, that will
                // be used to configure the pagination.
                // We'll make further calls to satisfy the user's request.
                _emitLimit = cmdletContext.MaxResult;
            }
            var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));

            var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);

            do
            {
                request.NextToken = _nextToken;
                if (_emitLimit.HasValue)
                {
                    int correctPageSize = AutoIterationHelpers.Min(500, _emitLimit.Value);
                    request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize);
                }

                CmdletOutput output;

                try
                {
                    var    response       = CallAWSServiceOperation(client, request);
                    object pipelineOutput = null;
                    if (!useParameterSelect)
                    {
                        pipelineOutput = cmdletContext.Select(response, this);
                    }
                    output = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };
                    int _receivedThisCall = response.Volumes.Count;

                    _nextToken       = response.NextToken;
                    _retrievedSoFar += _receivedThisCall;
                    if (_emitLimit.HasValue)
                    {
                        _emitLimit -= _receivedThisCall;
                    }
                }
                catch (Exception e)
                {
                    if (_retrievedSoFar == 0 || !_emitLimit.HasValue)
                    {
                        output = new CmdletOutput {
                            ErrorResponse = e
                        };
                    }
                    else
                    {
                        break;
                    }
                }

                ProcessOutput(output);
            } while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1));


            if (useParameterSelect)
            {
                WriteObject(cmdletContext.Select(null, this));
            }


            return(null);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeVolumes operation.
        /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeVolumes"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeVolumes operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public async Task<DescribeVolumesResponse> DescribeVolumesAsync(DescribeVolumesRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeVolumesRequestMarshaller();
            var unmarshaller = DescribeVolumesResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, DescribeVolumesRequest, DescribeVolumesResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
Exemplo n.º 20
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeVolumes operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeVolumes operation on AmazonEC2Client.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeVolumes
        ///         operation.</returns>
        public IAsyncResult BeginDescribeVolumes(DescribeVolumesRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new DescribeVolumesRequestMarshaller();
            var unmarshaller = DescribeVolumesResponseUnmarshaller.Instance;

            return BeginInvoke<DescribeVolumesRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
Exemplo n.º 21
0
		internal DescribeVolumesResponse DescribeVolumes(DescribeVolumesRequest request)
        {
            var task = DescribeVolumesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Describes the specified EBS volumes.
        /// 
        ///  
        /// <para>
        /// If you are describing a long list of volumes, you can paginate the output to make
        /// the list more manageable. The <code>MaxResults</code> parameter sets the maximum number
        /// of results returned in a single page. If the list of results exceeds your <code>MaxResults</code>
        /// value, then that number of results is returned along with a <code>NextToken</code>
        /// value that can be passed to a subsequent <code>DescribeVolumes</code> request to retrieve
        /// the remaining results.
        /// </para>
        ///  
        /// <para>
        /// For more information about EBS volumes, see <a href='http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html'>Amazon
        /// EBS Volumes</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the DescribeVolumes service method.</param>
        /// 
        /// <returns>The response from the DescribeVolumes service method, as returned by EC2.</returns>
        public DescribeVolumesResponse DescribeVolumes(DescribeVolumesRequest request)
        {
            var marshaller = new DescribeVolumesRequestMarshaller();
            var unmarshaller = DescribeVolumesResponseUnmarshaller.Instance;

            return Invoke<DescribeVolumesRequest,DescribeVolumesResponse>(request, marshaller, unmarshaller);
        }
Exemplo n.º 23
0
        /// <summary>
        /// <para>Describes the specified Amazon EBS volumes.</para> <para>For more information about Amazon EBS volumes, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html">Amazon EBS Volumes</a> in the <i>Amazon Elastic Compute Cloud
        /// User Guide</i> .</para>
        /// </summary>
        /// 
        /// <param name="describeVolumesRequest">Container for the necessary parameters to execute the DescribeVolumes service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeVolumes service method, as returned by AmazonEC2.</returns>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public Task<DescribeVolumesResponse> DescribeVolumesAsync(DescribeVolumesRequest describeVolumesRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeVolumesRequestMarshaller();
            var unmarshaller = DescribeVolumesResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, DescribeVolumesRequest, DescribeVolumesResponse>(describeVolumesRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
Exemplo n.º 24
0
 internal DescribeVolumesPaginator(IAmazonEC2 client, DescribeVolumesRequest request)
 {
     this._client  = client;
     this._request = request;
 }
Exemplo n.º 25
0
        public AWSVolume[] GetVolumes(IAmazonEC2 ec2Client = null, string[] volumeIds = null)
        {
            var ret = new List<AWSVolume>();

            var ec2 = ec2Client ?? GetEC2Client(); // might be passed in by instances calls...
            var request = new DescribeVolumesRequest();
            if (volumeIds != null && volumeIds.Length > 0)
            {
                request.VolumeIds = volumeIds.ToList();
            }

            var response = ec2.DescribeVolumes(request);

            foreach (var volume in response.Volumes)
            {
                var awsAttachments = new List<AWSAttachment>();
                foreach (var attachment in volume.Attachments)
                {
                    awsAttachments.Add(new AWSAttachment()
                        {
                            VolumeId = attachment.VolumeId,
                            InstanceId = attachment.InstanceId,
                            Device = attachment.Device,
                            Status = attachment.State.Value,
                            DeleteOnTermination = attachment.DeleteOnTermination,
                        });
                }

                var awsTags = new List<AWSTag>();
                foreach (var tag in volume.Tags)
                {
                    awsTags.Add(new AWSTag()
                        {
                            Key = tag.Key,
                            Value = tag.Value,
                        });
                }

                ret.Add(new AWSVolume()
                    {
                        VolumeId = volume.VolumeId,
                        VolumeType = volume.VolumeType,
                        SnapshotId = volume.SnapshotId,
                        Size = volume.Size,
                        Status = volume.State.Value,
                        IOPS = volume.Iops.ToString(),
                        Attachemnts = awsAttachments.ToArray(),
                        Tags = awsTags.ToArray(),
                    });
            }

            return ret.ToArray();
        }