Container for the parameters to the DescribeImages operation. Describes one or more of the images (AMIs, AKIs, and ARIs) available to you. Images available to you include public images, private images that you own, and private images owned by other AWS accounts but for which you have explicit launch permissions.

Deregistered images are included in the returned results for an unspecified interval after deregistration.

Inheritance: AmazonEC2Request
		//this quite an expensive operation (3M of data retrieved) - so I added caching support
		public static List<Image> getImagesList(this API_AmazonEC2 amazonEC2, AmazonEC2Client ec2Client)
		{										
			if (amazonEC2.CachedImageListRequest.fileExists())
				return amazonEC2.CachedImageListRequest.load<List<Amazon.EC2.Model.Image>>(); 
				
			var describeImagesRequest = new DescribeImagesRequest(); 				
			"Retrieving ImagesList from Amazon..".info();	
			var images = ec2Client.DescribeImages(describeImagesRequest)
					  .DescribeImagesResult.Image;
			if (images.isNull() || images.size()==0)
			{
				"in getImagesList, there was an error retrieving list (are we online?)".error();				
			}
			else
			{
				amazonEC2.CachedImageListRequest = images.save();
				"The Image List was saved to : {0}".info(amazonEC2.CachedImageListRequest);  
			}
			return images;
		}				
Ejemplo n.º 2
0
 public Image GetImage(Instance instance)
 {
     var imageId = instance.ImageId;
     var request = new DescribeImagesRequest {ImageIds = new List<string> {imageId}};
     var response = _ec2Client.DescribeImages(request);
     return response.Images.FirstOrDefault();
 }
Ejemplo n.º 3
0
        private Image GetSearchResults(string nameSearchField)
        {
            var request = new DescribeImagesRequest();
            request.ExecutableUsers.Add("all");
            request.Owners.Add("amazon");
            request.Filters = new List<Filter>
            {
                new Filter
                {
                    Name = "platform",
                    Values = new List<string>
                    {
                        "windows"
                    }
                },
                new Filter
                {
                    Name = "name",
                    Values = new List<string>
                    {
                        nameSearchField
                    }
                }
            };

            var results = _client.DescribeImages(request);
            var image = results.Images.Count > 1 ? FilterNewest(results.Images) : results.Images.Single();
            Logger.Info("Found image with id {0}, dated {1}", image.ImageId, GetDate(image.Name).ToString("yyyy-MM-dd"));
            return image;
        }
Ejemplo n.º 4
0
        public AWSImage GetImageById(string imageId)
        {
            var ec2 = GetEC2Client();

            var req = new DescribeImageAttributeRequest()
                          {
                              ImageId = imageId,
                              Attribute = new ImageAttributeName("description")
                          };
            var resp = ec2.DescribeImageAttribute(req);

            var request = new DescribeImagesRequest();
            //request.ImageIds = new List<string>(new[] { imageId });
            //request.ExecutableUsers = new List<string>(new[] { "all" });
            request.Filters =
                new List<Filter>(
                    new[] { new Filter() { Name = "image-id", Values = new List<string>(new[] { imageId }) } });

            var response = ec2.DescribeImages(request);

            var image = response.Images.SingleOrDefault();
            if (image == null)
            {
                return null;
            }

            var awsImage = GetAwsImageFromImage(image);
            return awsImage;
        }
Ejemplo n.º 5
0
 public List <Image> DescribeImages()
 {
     try
     {
         AWSModel.DescribeImagesRequest  request  = new AWSModel.DescribeImagesRequest();
         AWSModel.DescribeImagesResponse response = ec2.DescribeImages(request);
         List <Image> images = new List <Image>();
         if (response != null)
         {
             foreach (AWSModel.Image image in response.DescribeImagesResult.Image)
             {
                 if (image.ImageType.Equals("machine"))
                 {
                     Image vmImage = new Image();
                     vmImage.ImageId = image.ImageId;
                     vmImage.Name    = image.ImageLocation;
                     vmImage.State   = image.ImageState;
                     images.Add(vmImage);
                 }
             }
         }
         return(images);
     }
     catch (WebException e)
     {
         throw new MonoscapeEC2Exception(e.Message, e);
     }
     catch (AmazonEC2Exception e)
     {
         throw new MonoscapeEC2Exception(e.Message, e);
     }
 }
Ejemplo n.º 6
0
 public List<Image> GetImages(IEnumerable<string> imageIds)
 {
     var request = new DescribeImagesRequest
     {
         ImageIds = imageIds.AsList()
     };
     DescribeImagesResponse response = _ec2Client.DescribeImages(request);
     return response.Images;
 }
Ejemplo n.º 7
0
        public List<Image> GetImagesByTagName(string tagName)
        {
            var baseImageTagFilter = new Filter(_filterName, new List<string> {tagName});

            var request = new DescribeImagesRequest
            {
                Filters = new List<Filter> {baseImageTagFilter}
            };

            DescribeImagesResponse response = _ec2Client.DescribeImages(request);
            return response.Images;
        }
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;
            // create request
            var request = new Amazon.EC2.Model.DescribeImagesRequest();

            if (cmdletContext.ExecutableUser != null)
            {
                request.ExecutableUsers = cmdletContext.ExecutableUser;
            }
            if (cmdletContext.Filter != null)
            {
                request.Filters = cmdletContext.Filter;
            }
            if (cmdletContext.ImageId != null)
            {
                request.ImageIds = cmdletContext.ImageId;
            }
            if (cmdletContext.IncludeDeprecated != null)
            {
                request.IncludeDeprecated = cmdletContext.IncludeDeprecated.Value;
            }
            if (cmdletContext.Owner != null)
            {
                request.Owners = cmdletContext.Owner;
            }

            CmdletOutput output;

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

            try
            {
                var    response       = CallAWSServiceOperation(client, request);
                object pipelineOutput = null;
                pipelineOutput = cmdletContext.Select(response, this);
                output         = new CmdletOutput
                {
                    PipelineOutput  = pipelineOutput,
                    ServiceResponse = response
                };
            }
            catch (Exception e)
            {
                output = new CmdletOutput {
                    ErrorResponse = e
                };
            }

            return(output);
        }
Ejemplo n.º 9
0
        public override List<NodeImage> ListImages()
        {
            DescribeImagesRequest request = new DescribeImagesRequest ();
            DescribeImagesResponse response = Client.DescribeImages (request);

            List<NodeImage> res = new List<NodeImage> ();
            foreach (var i in response.DescribeImagesResult.Image) {
                Console.WriteLine ("location:   {0}", i.ImageLocation);
                res.Add (new NodeImage (i.ImageId, i.ImageLocation, this));
            }

            return res;
        }
Ejemplo n.º 10
0
        public override void Execute()
        {
            AmazonEC2Client client = new AmazonEC2Client(AWSAuthConnection.OUR_ACCESS_KEY_ID, AWSAuthConnection.OUR_SECRET_ACCESS_KEY);
            DescribeInstancesRequest request = new DescribeInstancesRequest();
            DescribeInstancesResponse response = client.DescribeInstances(request);

            Dictionary<string, List<RunningInstance>> instances = new Dictionary<string, List<RunningInstance>>();
            foreach (Reservation r in response.DescribeInstancesResult.Reservation)
                foreach (RunningInstance i in r.RunningInstance)
                {
                    if (!instances.ContainsKey(i.ImageId))
                        instances[i.ImageId] = new List<RunningInstance>();

                    instances[i.ImageId].Add(i);
                }

            List<string> allImageIds = new List<string>();
            foreach (string imageId in instances.Keys)
                allImageIds.Add(imageId);

            DescribeImagesRequest imageReq = new DescribeImagesRequest();
            imageReq.ImageId = allImageIds;
            DescribeImagesResponse imageResp = client.DescribeImages(imageReq);

            Dictionary<string, Image> imageDescriptions = new Dictionary<string, Image>();
            foreach (Image image in imageResp.DescribeImagesResult.Image)
                imageDescriptions.Add(image.ImageId, image);

            foreach (string imageId in instances.Keys)
            {
                if (imageDescriptions.ContainsKey(imageId))
                    Console.WriteLine("--- {0} {1} ({2} {3})",
                        imageId,
                        imageDescriptions[imageId].ImageLocation,
                        imageDescriptions[imageId].Platform,
                        imageDescriptions[imageId].Architecture);
                else
                    Console.WriteLine("--- {0} (AMI not found)", imageId);

                foreach (RunningInstance i in instances[imageId])
                {
                    DateTime launchTime = DateTime.Parse(i.LaunchTime);
                    Console.Write("{0}\t{1}\t{2}\t{3}\t{4}", launchTime, i.InstanceType, i.InstanceState.Name, i.InstanceId, i.StateTransitionReason);
                    if (ips)
                        Console.Write("\t{0}\t{1}", i.PublicDnsName, i.PrivateDnsName);
                    Console.WriteLine();
                }

                Console.WriteLine();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Query EC2 for the list of owned AMIs.
        /// </summary>
        protected override void AmazonExecute()
        {
            var request = new DescribeImagesRequest
            {
                Owner = new List<string> { this.Owner.Get(this.ActivityContext) }
            };

            try
            {
                var response = EC2Client.DescribeImages(request);
                this.Images.Set(this.ActivityContext, response.DescribeImagesResult.Image);
            }
            catch (EndpointNotFoundException ex)
            {
                this.LogBuildMessage(ex.Message);
            }
        }
 protected override void ProcessRecord()
 {
     AmazonEC2 client = base.GetClient();
     Amazon.EC2.Model.DescribeImagesRequest request = new Amazon.EC2.Model.DescribeImagesRequest();
     if (string.IsNullOrEmpty(this._ImageId))
     {
         request.ImageId.Add(this._ImageId);
     }
     if (string.IsNullOrEmpty(this._Owner))
     {
         request.Owner.Add(this._Owner);
     }
     if (string.IsNullOrEmpty(this._ExecutableBy))
     {
         request.ExecutableBy.Add(this._ExecutableBy);
     }
     Amazon.EC2.Model.DescribeImagesResponse response = client.DescribeImages(request);
     base.WriteObject(response.DescribeImagesResult.Image, true);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeImages operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeImages 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 EndDescribeImages
        ///         operation.</returns>
        public IAsyncResult BeginDescribeImages(DescribeImagesRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new DescribeImagesRequestMarshaller();
            var unmarshaller = DescribeImagesResponseUnmarshaller.Instance;

            return BeginInvoke<DescribeImagesRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
Ejemplo n.º 14
0
 IAsyncResult invokeDescribeImages(DescribeImagesRequest describeImagesRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new DescribeImagesRequestMarshaller().Marshall(describeImagesRequest);
     var unmarshaller = DescribeImagesResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
Ejemplo n.º 15
0
        public AWSImage[] GetImages()
        {
            var ret = new List<AWSImage>();

            var ec2 = GetEC2Client();
            var request = new DescribeImagesRequest();
            var response = ec2.DescribeImages(request);

            foreach (var image in response.Images)
            {
                var awsImage = GetAwsImageFromImage(image);
                ret.Add(awsImage);
            }

            return ret.ToArray();
        }
Ejemplo n.º 16
0
 /// <summary>
 /// <para>Describes one or more of the images (AMIs, AKIs, and ARIs) available to you. Images available to you include public images, private
 /// images that you own, and private images owned by other AWS accounts but for which you have explicit launch permissions.</para>
 /// <para><b>NOTE:</b> Deregistered images are included in the returned results for an unspecified interval after deregistration. </para>
 /// </summary>
 /// 
 /// <param name="describeImagesRequest">Container for the necessary parameters to execute the DescribeImages service method on
 ///          AmazonEC2.</param>
 /// 
 /// <returns>The response from the DescribeImages service method, as returned by AmazonEC2.</returns>
 /// 
 public DescribeImagesResponse DescribeImages(DescribeImagesRequest describeImagesRequest)
 {
     IAsyncResult asyncResult = invokeDescribeImages(describeImagesRequest, null, null, true);
     return EndDescribeImages(asyncResult);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Initiates the asynchronous execution of the DescribeImages operation.
 /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeImages"/>
 /// </summary>
 /// 
 /// <param name="describeImagesRequest">Container for the necessary parameters to execute the DescribeImages 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 EndDescribeImages
 ///         operation.</returns>
 public IAsyncResult BeginDescribeImages(DescribeImagesRequest describeImagesRequest, AsyncCallback callback, object state)
 {
     return invokeDescribeImages(describeImagesRequest, callback, state, false);
 }
Ejemplo n.º 18
0
		internal DescribeImagesResponse DescribeImages(DescribeImagesRequest request)
        {
            var task = DescribeImagesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// <para>Describes one or more of the images (AMIs, AKIs, and ARIs) available to you. Images available to you include public images, private
        /// images that you own, and private images owned by other AWS accounts but for which you have explicit launch permissions.</para>
        /// <para><b>NOTE:</b> Deregistered images are included in the returned results for an unspecified interval after deregistration. </para>
        /// </summary>
        /// 
        /// <param name="describeImagesRequest">Container for the necessary parameters to execute the DescribeImages service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeImages 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<DescribeImagesResponse> DescribeImagesAsync(DescribeImagesRequest describeImagesRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeImagesRequestMarshaller();
            var unmarshaller = DescribeImagesResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, DescribeImagesRequest, DescribeImagesResponse>(describeImagesRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// <para> The DescribeImages operation returns information about AMIs, AKIs, and ARIs available to the user. Information returned includes
        /// image type, product codes, architecture, and kernel and RAM disk IDs. Images available to the user include public images available for any
        /// user to launch, private images owned by the user making the request, and private images owned by other users for which the user has explicit
        /// launch permissions. </para> <para> Launch permissions fall into three categories: </para>
        /// <ul>
        /// <li> <b>Public:</b> The owner of the AMI granted launch permissions for the AMI to the all group. All users have launch permissions for
        /// these AMIs. </li>
        /// <li> <b>Explicit:</b> The owner of the AMI granted launch permissions to a specific user. </li>
        /// <li> <b>Implicit:</b> A user has implicit launch permissions for all AMIs he or she owns. </li>
        /// 
        /// </ul>
        /// <para> The list of AMIs returned can be modified by specifying AMI IDs, AMI owners, or users with launch permissions. If no options are
        /// specified, Amazon EC2 returns all AMIs for which the user has launch permissions. </para> <para> If you specify one or more AMI IDs, only
        /// AMIs that have the specified IDs are returned. If you specify an invalid AMI ID, a fault is returned. If you specify an AMI ID for which you
        /// do not have access, it will not be included in the returned results. </para> <para> If you specify one or more AMI owners, only AMIs from
        /// the specified owners and for which you have access are returned. The results can include the account IDs of the specified owners, amazon for
        /// AMIs owned by Amazon or self for AMIs that you own. </para> <para> If you specify a list of executable users, only users that have launch
        /// permissions for the AMIs are returned. You can specify account IDs (if you own the AMI(s)), self for AMIs for which you own or have explicit
        /// permissions, or all for public AMIs. </para> <para><b>NOTE:</b> Deregistered images are included in the returned results for an unspecified
        /// interval after deregistration. </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeImages service method on
        /// AmazonEC2.</param>
        /// 
        /// <returns>The response from the DescribeImages service method, as returned by AmazonEC2.</returns>
		public DescribeImagesResponse DescribeImages(DescribeImagesRequest request)
        {
            var task = DescribeImagesAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeImages operation.
        /// <seealso cref="Amazon.EC2.IAmazonEC2.DescribeImages"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeImages 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<DescribeImagesResponse> DescribeImagesAsync(DescribeImagesRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeImagesRequestMarshaller();
            var unmarshaller = DescribeImagesResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, DescribeImagesRequest, DescribeImagesResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// The DescribeImages operation returns information about AMIs, AKIs, and ARIs
        /// available to the user. Information returned includes image type, product codes,
        /// architecture, and kernel and RAM disk IDs. Images available to the user include
        /// public images available for any user to launch, private images owned by the
        /// user making the request, and private images owned by other users for which the
        /// user has explicit launch permissions.
        /// Launch permissions fall into three categories:
        /// Public:
        /// The owner of the AMI granted launch permissions for the AMI to the all group.
        /// All users have launch permissions for these AMIs.
        /// Explicit:
        /// The owner of the AMI granted launch permissions to a specific user.
        /// Implicit:
        /// A user has implicit launch permissions for all AMIs he or she owns.
        /// The list of AMIs returned can be modified by specifying AMI IDs, AMI owners, or
        /// users with launch permissions. If no options are specified, Amazon EC2 returns
        /// all AMIs for which the user has launch permissions.
        /// If you specify one or more AMI IDs, only AMIs that have the specified IDs are
        /// returned. If you specify an invalid AMI ID, a fault is returned. If you specify
        /// an AMI ID for which you do not have access, it will not be included in the
        /// returned results.
        /// If you specify one or more AMI owners, only AMIs from the specified owners and
        /// for which you have access are returned. The results can include the account IDs
        /// of the specified owners, amazon for AMIs owned by Amazon or self for AMIs that
        /// you own.
        /// If you specify a list of executable users, only users that have launch
        /// permissions for the AMIs are returned. You can specify account IDs (if you own
        /// the AMI(s)), self for AMIs for which you own or have explicit permissions, or
        /// all for public AMIs.
        /// Note:
        /// Deregistered images are included in the returned results for an unspecified
        /// interval after deregistration.
        /// 
        /// </summary>
        /// <param name="service">Instance of AmazonEC2 service</param>
        /// <param name="request">DescribeImagesRequest request</param>
        public static void InvokeDescribeImages(AmazonEC2 service, DescribeImagesRequest request)
        {
            try 
            {
                DescribeImagesResponse response = service.DescribeImages(request);
                
                
                Console.WriteLine ("Service Response");
                Console.WriteLine ("=============================================================================");
                Console.WriteLine ();

                Console.WriteLine("        DescribeImagesResponse");
                if (response.IsSetResponseMetadata())
                {
                    Console.WriteLine("            ResponseMetadata");
                    ResponseMetadata  responseMetadata = response.ResponseMetadata;
                    if (responseMetadata.IsSetRequestId())
                    {
                        Console.WriteLine("                RequestId");
                        Console.WriteLine("                    {0}", responseMetadata.RequestId);
                    }
                }
                if (response.IsSetDescribeImagesResult())
                {
                    Console.WriteLine("            DescribeImagesResult");
                    DescribeImagesResult  describeImagesResult = response.DescribeImagesResult;
                    List<Image> imageList = describeImagesResult.Image;
                    foreach (Image image in imageList)
                    {
                        Console.WriteLine("                Image");
                        if (image.IsSetImageId())
                        {
                            Console.WriteLine("                    ImageId");
                            Console.WriteLine("                        {0}", image.ImageId);
                        }
                        if (image.IsSetImageLocation())
                        {
                            Console.WriteLine("                    ImageLocation");
                            Console.WriteLine("                        {0}", image.ImageLocation);
                        }
                        if (image.IsSetImageState())
                        {
                            Console.WriteLine("                    ImageState");
                            Console.WriteLine("                        {0}", image.ImageState);
                        }
                        if (image.IsSetOwnerId())
                        {
                            Console.WriteLine("                    OwnerId");
                            Console.WriteLine("                        {0}", image.OwnerId);
                        }
                        if (image.IsSetVisibility())
                        {
                            Console.WriteLine("                    Visibility");
                            Console.WriteLine("                        {0}", image.Visibility);
                        }
                        List<String> productCodeList  =  image.ProductCode;
                        foreach (String productCode in productCodeList)
                        {
                            Console.WriteLine("                    ProductCode");
                            Console.WriteLine("                        {0}", productCode);
                        }
                        if (image.IsSetArchitecture())
                        {
                            Console.WriteLine("                    Architecture");
                            Console.WriteLine("                        {0}", image.Architecture);
                        }
                        if (image.IsSetImageType())
                        {
                            Console.WriteLine("                    ImageType");
                            Console.WriteLine("                        {0}", image.ImageType);
                        }
                        if (image.IsSetKernelId())
                        {
                            Console.WriteLine("                    KernelId");
                            Console.WriteLine("                        {0}", image.KernelId);
                        }
                        if (image.IsSetRamdiskId())
                        {
                            Console.WriteLine("                    RamdiskId");
                            Console.WriteLine("                        {0}", image.RamdiskId);
                        }
                        if (image.IsSetPlatform())
                        {
                            Console.WriteLine("                    Platform");
                            Console.WriteLine("                        {0}", image.Platform);
                        }
                    }
                }

            } 
            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);
            }
        }
 private Amazon.EC2.Model.DescribeImagesResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.DescribeImagesRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "DescribeImages");
     try
     {
         #if DESKTOP
         return(client.DescribeImages(request));
         #elif CORECLR
         return(client.DescribeImagesAsync(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;
     }
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets the data for EC2 Instances in a given Profile and Region.
        /// </summary>
        /// <param name="aprofile"></param>
        /// <param name="Region2Scan"></param>
        /// <returns></returns>
        public DataTable GetEC2Instances(string aprofile, string Region2Scan)
        {
            DataTable ToReturn = AWSTables.GetComponentTable("EC2");
            RegionEndpoint Endpoint2scan = RegionEndpoint.USEast1;
            Amazon.Runtime.AWSCredentials credential;
            credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
            //Convert the Region2Scan to an AWS Endpoint.
            foreach (var aregion in RegionEndpoint.EnumerableAllRegions)
            {
                if (aregion.DisplayName.Equals(Region2Scan))
                {
                    Endpoint2scan = aregion;
                    continue;
                }
            }

            var ec2 = new Amazon.EC2.AmazonEC2Client(credential, Endpoint2scan);
            string accountid = GetAccountID(aprofile);
            var request = new DescribeInstanceStatusRequest();



            

            request.IncludeAllInstances = true;
            DescribeInstanceStatusResponse instatresponse = new DescribeInstanceStatusResponse();
            var indatarequest = new DescribeInstancesRequest();
            try
            {
                instatresponse = ec2.DescribeInstanceStatus(request);
            }
            catch (Exception ex)
            {
                string test = "";//Quepaso? 
            }

            //Get a list of the InstanceIDs.
            foreach (var instat in instatresponse.InstanceStatuses)
            {
                indatarequest.InstanceIds.Add(instat.InstanceId);
                indatarequest.InstanceIds.Sort();
            }

            DescribeInstancesResponse DescResult = ec2.DescribeInstances();
           
            int count = instatresponse.InstanceStatuses.Count();

            //Build data dictionary of instances
            Dictionary<String, Instance> Bunchadata = new Dictionary<string, Instance>();
            foreach (var urtburgle in DescResult.Reservations)
            {
                foreach (var instancedata in urtburgle.Instances)
                {
                    try { Bunchadata.Add(instancedata.InstanceId, instancedata); }
                    catch (Exception ex) {
                        var ff ="";//a duplicate??
                    };
                }
            }

            //Go through list of instances...
            foreach (var instat in instatresponse.InstanceStatuses)
            {
                
                string instanceid = instat.InstanceId;
                Instance thisinstance = new Instance();
                try
                {
                    thisinstance = Bunchadata[instanceid];
                }
                catch(Exception ex)
                {

                    continue;
                }
                DataRow thisinstancedatarow = ToReturn.NewRow();
                //Collect the datases
                string instancename = "";
                var status = instat.Status.Status;
                string AZ = instat.AvailabilityZone;
                var istate = instat.InstanceState.Name;

                string profile = aprofile;
                string myregion = Region2Scan;
                int eventnumber = instat.Events.Count();
                List<string> eventlist = new List<string>();
                var reservations = DescResult.Reservations;

                var myinstance = new Reservation();

                var atreq = new DescribeInstanceAttributeRequest();
                atreq.InstanceId = instanceid;
                atreq.Attribute = "disableApiTermination";
                var atresp = ec2.DescribeInstanceAttribute(atreq).InstanceAttribute;
                string TerminationProtection = atresp.DisableApiTermination.ToString();

                List<String> innies = new List<String>();
                foreach (Reservation arez in DescResult.Reservations)
                {
                    var checky = arez.Instances[0].InstanceId;
                    innies.Add(checky);
                    if (arez.Instances[0].InstanceId.Equals(instanceid))
                    {
                        myinstance = arez;
                    }
                }
                innies.Sort();

                List<string> tags = new List<string>();
                var loadtags = thisinstance.Tags.AsEnumerable();
                foreach (var atag in loadtags)
                {
                    tags.Add(atag.Key + ": " + atag.Value);
                    if (atag.Key.Equals("Name")) instancename = atag.Value;
                }

                Dictionary<string, string> taglist = new Dictionary<string, string>();
                foreach (var rekey in loadtags)
                {
                    taglist.Add(rekey.Key, rekey.Value);
                }

                if (eventnumber > 0)
                {
                    foreach (var anevent in instat.Events)
                    {
                        eventlist.Add(anevent.Description);
                    }
                }
                String platform = "";
                try { platform = thisinstance.Platform.Value; }
                catch { platform = "Linux"; }
                if (String.IsNullOrEmpty(platform)) platform = "Linux";


                String Priv_IP = "";
                try { Priv_IP = thisinstance.PrivateIpAddress; }
                catch { }
                if (String.IsNullOrEmpty(Priv_IP))
                {
                    Priv_IP = "?";
                }
                
                String disinstance = thisinstance.InstanceId;

                String publicIP = "";
                try { publicIP = thisinstance.PublicIpAddress; }
                catch { }
                if (String.IsNullOrEmpty(publicIP)) publicIP = "";

                

                String publicDNS = "";
                try { publicDNS = thisinstance.PublicDnsName; }
                catch { }
                if (String.IsNullOrEmpty(publicDNS)) publicDNS = "";

                string myvpcid = "";
                try
                { myvpcid = thisinstance.VpcId; }
                catch { }
                if (String.IsNullOrEmpty(myvpcid)) myvpcid = "";
                

                string mysubnetid = "";
                try { mysubnetid = thisinstance.SubnetId; }
                catch { }
                if (String.IsNullOrEmpty(mysubnetid)) mysubnetid = "";


                //Virtualization type (HVM, Paravirtual)
                string ivirtType = "";
                try
                { ivirtType = thisinstance.VirtualizationType; }
                catch { }
                if (String.IsNullOrEmpty(ivirtType)) ivirtType = "?";

                // InstanceType (m3/Large etc)
                String instancetype = "";
                try
                { instancetype = thisinstance.InstanceType.Value; }
                catch { }
                if (String.IsNullOrEmpty(instancetype)) instancetype = "?";


                //Test section to try to pull out AMI data
                string AMI = "";
                string AMIName = "";
                string AMIDesc = "";
                string AMILocation = "";
                string AMIState = "";
                try { AMI = thisinstance.ImageId; }
                catch { }
                if (string.IsNullOrEmpty(AMI)) AMI = "";
                else
                {
                    DescribeImagesRequest DIR = new DescribeImagesRequest();
                    DIR.ImageIds.Add(AMI);
                    var imresp = ec2.DescribeImages(DIR);
                    var idata = imresp.Images;
                    try {
                        if (idata.Count > 0)
                        {
                            AMIDesc = idata[0].Description;
                            AMIName = idata[0].Name;
                            AMILocation = idata[0].ImageLocation;
                            AMIState = idata[0].State;

                        }
                        else
                        {
                            AMIDesc = "na";
                            AMIName = "na";
                            AMILocation = "na";
                            AMIState = "na";
                        }
                        if (String.IsNullOrEmpty(AMIDesc)) { AMIDesc = ""; }
                        if (String.IsNullOrEmpty(AMIName)) { AMIName = ""; }
                    }
                    catch(Exception ex)
                    {
                        string whyforerror = ex.Message;
                    }
                 
                }

                //
                var SGs = thisinstance.SecurityGroups;
                List<string> SGids = new List<string>();
                List<String> SGNames = new List<string>();
                foreach (var wabbit in SGs)
                {
                    SGids.Add(wabbit.GroupId);
                    SGNames.Add(wabbit.GroupName);
                }



                //Add to table
                if (SGids.Count < 1) SGids.Add("NullOrEmpty");
                if (SGNames.Count < 1) SGNames.Add("");
                if (String.IsNullOrEmpty(SGids[0])) SGids[0] = "NullOrEmpty";
                if (String.IsNullOrEmpty(SGNames[0])) SGNames[0] = "";

                if (String.IsNullOrEmpty(instancename)) instancename = "";


                //EC2DetailsTable.Rows.Add(accountid, profile, myregion, instancename, instanceid, AMI, AMIDesc, AZ, platform, status, eventnumber, eventlist, tags, Priv_IP, publicIP, publicDNS, istate, ivirtType, instancetype, sglist);
                //Is list for Profile and Region, so can key off of InstanceID. In theory InstanceID is unique

                //Build our dictionary of values and keys for this instance  This is dependent on the table created by GetEC2DetailsTable()
                Dictionary<string, string> datafields = new Dictionary<string, string>();
                thisinstancedatarow["AccountID"] = accountid;
                thisinstancedatarow["Profile"] = profile;
                thisinstancedatarow["Region"] = myregion;
                thisinstancedatarow["InstanceName"] = instancename;
                thisinstancedatarow["InstanceID"] = instanceid;
                thisinstancedatarow["TerminationProtection"] = TerminationProtection;
                thisinstancedatarow["AMI"] = AMI;
                thisinstancedatarow["AMIState"] = AMIState;
                thisinstancedatarow["AMILocation"] = AMILocation;
                thisinstancedatarow["AMIDescription"] = AMIDesc;
                thisinstancedatarow["AvailabilityZone"] = AZ;
                thisinstancedatarow["Status"] = status;
                thisinstancedatarow["Events"] = eventnumber.ToString();
                thisinstancedatarow["EventList"] = List2String(eventlist);
                thisinstancedatarow["Tags"] = List2String(tags);
                thisinstancedatarow["PrivateIP"] = Priv_IP;
                thisinstancedatarow["PublicIP"] = publicIP;
                thisinstancedatarow["PublicDNS"] = publicDNS;
                thisinstancedatarow["PublicDNS"] = publicDNS;
                thisinstancedatarow["VPC"] = myvpcid;
                thisinstancedatarow["SubnetID"] = mysubnetid;
                thisinstancedatarow["InstanceState"] = istate.Value;
                thisinstancedatarow["VirtualizationType"] = ivirtType;
                thisinstancedatarow["InstanceType"] = instancetype;
                thisinstancedatarow["SecurityGroups"] = List2String(SGids);
                thisinstancedatarow["SGNames"] = List2String(SGNames);
                //Add this instance to the data returned.
                ToReturn.Rows.Add(thisinstancedatarow);


            }//End for of instances



            return ToReturn;
        }//EndGetEC2
Ejemplo n.º 25
0
        /// <summary>
        /// Describes one or more of the images (AMIs, AKIs, and ARIs) available to you. Images
        /// available to you include public images, private images that you own, and private images
        /// owned by other AWS accounts but for which you have explicit launch permissions.
        /// 
        ///  <note>
        /// <para>
        /// Deregistered images are included in the returned results for an unspecified interval
        /// after deregistration.
        /// </para>
        /// </note>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the DescribeImages service method.</param>
        /// 
        /// <returns>The response from the DescribeImages service method, as returned by EC2.</returns>
        public DescribeImagesResponse DescribeImages(DescribeImagesRequest request)
        {
            var marshaller = new DescribeImagesRequestMarshaller();
            var unmarshaller = DescribeImagesResponseUnmarshaller.Instance;

            return Invoke<DescribeImagesRequest,DescribeImagesResponse>(request, marshaller, unmarshaller);
        }
Ejemplo n.º 26
0
        public List<CEc2Ami> describeImages(string owner)
        {
            List<CEc2Ami> amis = new List<CEc2Ami>();

            try
            {
                DescribeImagesRequest request = new DescribeImagesRequest();
                if (string.IsNullOrEmpty(owner) == false)
                {
                    List<string> owners = new List<string>();
                    owners.Add(owner);
                    request.Owner = owners;
                }

                DescribeImagesResponse response = _service.DescribeImages(request);

                if (response.IsSetDescribeImagesResult())
                {
                    DescribeImagesResult describeImagesResult = response.DescribeImagesResult;
                    List<Image> imageList = describeImagesResult.Image;
                    foreach (Image image in imageList)
                    {
                        CEc2Ami ami = new CEc2Ami();
                        if (image.IsSetImageId())
                        {
                            ami.imageId = image.ImageId;
                        }
                        if (image.IsSetImageLocation())
                        {
                            ami.imageLocation = image.ImageLocation;
                        }
                        if (image.IsSetArchitecture())
                        {
                            ami.architecture = image.Architecture;
                        }
                        if (image.IsSetImageType())
                        {
                            ami.imageType = image.ImageType;
                        }
                        if (image.IsSetPlatform())
                        {
                            ami.platform = image.Platform;
                        }

                        amis.Add(ami);
                    }
                }
            }
            catch (AmazonEC2Exception ex)
            {
                throw new Exception("Caught Exception: " + ex.XML);
            }

            return amis;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Initiates the asynchronous execution of the DescribeImages operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the DescribeImages 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<DescribeImagesResponse> DescribeImagesAsync(DescribeImagesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeImagesRequestMarshaller();
            var unmarshaller = DescribeImagesResponseUnmarshaller.Instance;

            return InvokeAsync<DescribeImagesRequest,DescribeImagesResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
Ejemplo n.º 28
0
 public List<Image> DescribeImages()
 {
     try
     {
         AWSModel.DescribeImagesRequest request = new AWSModel.DescribeImagesRequest();
         AWSModel.DescribeImagesResponse response = ec2.DescribeImages(request);
         List<Image> images = new List<Image>();
         if (response != null)
         {
             foreach (AWSModel.Image image in response.DescribeImagesResult.Image)
             {
                 if(image.ImageType.Equals("machine"))
                 {
                     Image vmImage = new Image();
                     vmImage.ImageId = image.ImageId;
                     vmImage.Name = image.ImageLocation;
                     vmImage.State = image.ImageState;
                     images.Add(vmImage);
                 }
             }
         }
         return images;
     }
     catch (WebException e)
     {
         throw new MonoscapeEC2Exception(e.Message, e);
     }
     catch (AmazonEC2Exception e)
     {
         throw new MonoscapeEC2Exception(e.Message, e);
     }
 }