コード例 #1
0
        public async System.Threading.Tasks.Task TestDescribeAmazonImagesCancellationTest()
        {
            // perform a filtered query to (a) test parameter marshalling
            // and (b) cut down the time to run -- an unfiltered request
            // yields a lot of images
            var request = new DescribeImagesRequest();

            request.Owners.Add("amazon");

            var cts = new CancellationTokenSource();

            cts.CancelAfter(1000);
            var token = cts.Token;

            try
            {
                var response = await Client.DescribeImagesAsync(request, token);
            }
            catch (OperationCanceledException exception)
            {
                Assert.AreEqual(token, exception.CancellationToken);
                Assert.AreEqual(true, exception.CancellationToken.IsCancellationRequested);
                return;
            }
            Assert.Fail("An OperationCanceledException was not thrown");
        }
コード例 #2
0
        public void EcsRequestTest()
        {
            var request  = new DescribeImagesRequest();
            var response = FeatureTest.DefaultClient.GetAcsResponse(request);

            Assert.NotNull(response);
        }
コード例 #3
0
        private static async Task DeleteOrphanSnapshots()
        {
            var client = new AmazonEC2Client(RegionEndpoint.APSoutheast2);
            var describeSnapshotRequest = new DescribeSnapshotsRequest();

            describeSnapshotRequest.OwnerIds.Add(ownerId);

            var snapshots = await client.DescribeSnapshotsAsync(describeSnapshotRequest);

            var describeImagesRequest = new DescribeImagesRequest();

            describeImagesRequest.Owners.Add(ownerId);

            var images = await client.DescribeImagesAsync(describeImagesRequest);

            const int numberOfdaysToKeepImage = 30;

            foreach (var snapshot in snapshots.Snapshots.Where(s =>
                                                               !images.Images.Any(i => i.BlockDeviceMappings.Any(d => d.Ebs.SnapshotId == s.SnapshotId)) &&
                                                               DateTime.Today.Subtract(s.StartTime).Days > numberOfdaysToKeepImage))
            {
                Console.WriteLine($"Deleting snapshot {snapshot.Description}...");
                await client.DeleteSnapshotAsync(new DeleteSnapshotRequest(snapshot.SnapshotId));
            }
        }
コード例 #4
0
        public static void DescribeImages(AmazonEC2Client client)
        {
            var owners = new List <String>();

            owners.Add("amazon");
            var filterOwner = new Filter("owner-alias", owners);

            var platforms = new List <string>();

            platforms.Add("windows");
            var filterPlatform = new Filter("platform", platforms);

            var architectures = new List <string>();

            architectures.Add("x86_64");
            var filterArchitecture = new Filter("architecture", architectures);


            var request = new DescribeImagesRequest();

            request.Filters.Add(filterOwner);
            request.Filters.Add(filterPlatform);
            // request.ExecutableUsers.Add("self");
            request.ImageIds.Add("ami-1712d877");

            List <Image> result = client.DescribeImages(request).Images;

            foreach (Image img in result)
            {
                Console.WriteLine("{0}: \t{1})", img.ImageId, img.Name);
            }
        }
コード例 #5
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonAppStreamConfig config = new AmazonAppStreamConfig();

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

            DescribeImagesResponse resp = new DescribeImagesResponse();

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

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

                foreach (var obj in resp.Images)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
コード例 #6
0
        public async Task <ContainerImage> GetImage(string repository, string tag)
        {
            var repositories = await GetRepositoriesInternal();

            var repo = repositories.First(x => x.repositoryUri == repository);

            var describeImagesRequest = new DescribeImagesRequest()
            {
                ImageIds = new List <ImageIdentifier>()
                {
                    new ImageIdentifier()
                    {
                        ImageTag = tag
                    }
                },
                RegistryId     = repo.registryId,
                RepositoryName = repo.repositoryName,
            };

            var images = await _client.DescribeImagesAsync(describeImagesRequest, CancellationToken.None);

            return(images.ImageDetails.SelectMany(
                       i => i.ImageTags,
                       (i, tag) => new ContainerImage(repository, tag, i.ImageDigest, i.ImagePushedAt)
                       )
                   .First());
        }
コード例 #7
0
        public List <Image> GetAllOwnedPrivateAMIs(ILambdaContext context)
        {
            String accountId        = context.InvokedFunctionArn.Split(':')[4];
            var    ec2Client        = new AmazonEC2Client();
            var    asClient         = new AmazonAutoScalingClient();
            var    getImagesRequest = new DescribeImagesRequest();
            var    getLCRequest     = new DescribeLaunchConfigurationsRequest();

            getLCRequest.MaxRecords = 100;

            getImagesRequest.Filters.Add(new Amazon.EC2.Model.Filter
            {
                Name   = "is-public",
                Values = new List <string>()
                {
                    "false"
                }
            });
            getImagesRequest.Filters.Add(new Amazon.EC2.Model.Filter
            {
                Name   = "owner-id",
                Values = new List <string>()
                {
                    accountId
                }
            });

            var imagesResponse = ec2Client.DescribeImagesAsync(getImagesRequest);

            imagesResponse.Wait();

            return(imagesResponse.Result.Images);
        }
コード例 #8
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);
        }
コード例 #9
0
        internal DescribeImagesResponse DescribeImages(DescribeImagesRequest request)
        {
            var marshaller   = new DescribeImagesRequestMarshaller();
            var unmarshaller = DescribeImagesResponseUnmarshaller.Instance;

            return(Invoke <DescribeImagesRequest, DescribeImagesResponse>(request, marshaller, unmarshaller));
        }
コード例 #10
0
ファイル: ZAwsCloudController.cs プロジェクト: kueiwa/ZAws
        private DescribeImagesResponse GetAmis()
        {
            DescribeImagesRequest request = new DescribeImagesRequest()
                                            .WithOwner("self");
            DescribeImagesResponse resp = ec2.DescribeImages(request);

            return(resp);
        }
コード例 #11
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>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/DescribeImages">REST API Reference for DescribeImages Operation</seealso>
        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));
        }
コード例 #12
0
        public Image GetImage(string imageId)
        {
            var imageRequest = new DescribeImagesRequest
            {
                ImageIds = new[] { imageId }.ToList()
            };

            return(GetImages(imageRequest).Last());
        }
コード例 #13
0
ファイル: AWSEC2Utils.cs プロジェクト: ohga/USIEngineOnAWS
 public bool load_image_id(string vm_type)
 {
     write_log(region + " のマシンイメージを確認しています。");
     try
     {
         string tmp = setting_.getValueString("common", "image_id");
         if (tmp != null && tmp.Length != 0)
         {
             image_id = tmp;
             write_log("マシンイメージ " + image_id + " を使用します。");
             return(true);
         }
     }
     catch
     {
         //none
     }
     try
     {
         var client    = get_client();
         var query_req = new DescribeImagesRequest();
         query_req.Filters.Add(new Filter()
         {
             Name = "name", Values = new List <string>()
             {
                 "*/images/*/ubuntu-*-16.04-*"
             }
         });
         query_req.Filters.Add(new Filter()
         {
             Name = "virtualization-type", Values = new List <string>()
             {
                 vm_type
             }
         });
         if (vm_type == "hvm")
         {
             query_req.Filters.Add(new Filter()
             {
                 Name = "root-device-type", Values = new List <string>()
                 {
                     "ebs"
                 }
             });
         }
         var query_res = client.DescribeImages(query_req);
         Amazon.EC2.Model.Image[] images = query_res.Images.ToArray();
         images   = images.OrderByDescending(n => n.CreationDate).ToArray();
         image_id = images[0].ImageId;
     }
     catch (Exception ex)
     {
         write_log("ERROR: " + ex.ToString());
         return(false);
     }
     return(true);
 }
コード例 #14
0
        private IEnumerable <Image> GetImages(DescribeImagesRequest imageRequest)
        {
            var response = _client.DescribeImages(imageRequest);

            if (response.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new DescribeImagesException(response.HttpStatusCode.ToString());
            }
            return(response.Images);
        }
コード例 #15
0
        public List <Image> GetImages(IEnumerable <string> imageIds)
        {
            var request = new DescribeImagesRequest
            {
                ImageIds = imageIds.AsList()
            };
            DescribeImagesResponse response = _ec2Client.DescribeImages(request);

            return(response.Images);
        }
コード例 #16
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);
        }
コード例 #17
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());
        }
コード例 #18
0
        DescribeImagesResponse GetAMIs(List <Filter> searchFilters)
        {
            DescribeImagesResponse result = null;

            using (AmazonEC2Client EC2client = new AmazonEC2Client(creds))
            {
                DescribeImagesRequest rq = new DescribeImagesRequest();
                rq.Filters = searchFilters;
                result     = EC2client.DescribeImages(rq);
            }

            return(result);
        }
コード例 #19
0
        public void TestDescribeAmazonImages()
        {
            // perform a filtered query to (a) test parameter marshalling
            // and (b) cut down the time to run -- an unfiltered request
            // yields a lot of images
            var request = new DescribeImagesRequest();

            request.Owners.Add("amazon");
            var response = Client.DescribeImagesAsync(request).Result;

            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Images);
        }
コード例 #20
0
        public async Task <IEnumerable <ContainerImage> > GetRepositoryTags(string repository)
        {
            using (_log.BeginScope(new Dictionary <string, object>()
            {
                { "Repository", repository }
            }))
            {
                _log.LogTrace("Getting repository tags");

                var repositories = await GetRepositoriesInternal();

                // var repositories = await _client.DescribeRepositoriesAsync(new DescribeRepositoriesRequest());
                var repo = repositories.First(r =>
                                              r.repositoryUri.Equals(repository, StringComparison.OrdinalIgnoreCase));

                var describeImagesRequest = new DescribeImagesRequest()
                {
                    RegistryId     = repo.registryId,
                    RepositoryName = repo.repositoryName,
                };

                var images = await _client.DescribeImagesAsync(describeImagesRequest, CancellationToken.None);

                _log.LogTrace("Building image list");
                var imageList = images.ImageDetails.SelectMany(
                    i => i.ImageTags,
                    (i, tag) => new ContainerImage(repository, tag, i.ImageDigest, i.ImagePushedAt)
                    )

                                .ToList();

                while (images.NextToken != null)
                {
                    describeImagesRequest.NextToken = images.NextToken;
                    images = await _client.DescribeImagesAsync(describeImagesRequest);

                    imageList.AddRange(
                        images.ImageDetails.SelectMany(
                            i => i.ImageTags,
                            (i, tag) => new ContainerImage(repository, tag, i.ImageDigest, i.ImagePushedAt)
                            )
                        );
                }

                _log.LogTrace("Found {ImageCount} images for {Repository}", imageList.Count, repository);

                return(imageList);
            }
        }
コード例 #21
0
        /// <summary>
        /// 获取指定图片库中的图片列表。
        /// </summary>
        /// <param name="req"><see cref="DescribeImagesRequest"/></param>
        /// <returns><see cref="DescribeImagesResponse"/></returns>
        public DescribeImagesResponse DescribeImagesSync(DescribeImagesRequest req)
        {
            JsonResponseModel <DescribeImagesResponse> rsp = null;

            try
            {
                var strResp = this.InternalRequestSync(req, "DescribeImages");
                rsp = JsonConvert.DeserializeObject <JsonResponseModel <DescribeImagesResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
コード例 #22
0
        public async Task <List <AMImage> > DescribeImages()
        {
            DescribeImagesRequest request = new DescribeImagesRequest();

            request.Owners.Add(_accountId);
            DescribeImagesResponse response = await _ec2Client.DescribeImagesAsync(request);

            List <AMImage> amiImages = new List <AMImage>();

            foreach (var item in response.Images)
            {
                amiImages.Add(new AMImage(item.ImageId, item.Name, item.Description, item.CreationDate, item.Architecture, item.Platform, item.State, item.OwnerId));
            }

            return(amiImages);
        }
コード例 #23
0
        private String getImagesAsCsv(ILambdaContext context)
        {
            String accountId        = context.InvokedFunctionArn.Split(':')[4];
            var    ec2Client        = new AmazonEC2Client();
            var    asClient         = new AmazonAutoScalingClient();
            var    getImagesRequest = new DescribeImagesRequest();
            var    getLCRequest     = new DescribeLaunchConfigurationsRequest();

            getLCRequest.MaxRecords = 100;


            getImagesRequest.Filters.Add(new Amazon.EC2.Model.Filter
            {
                Name   = "is-public",
                Values = new List <string>()
                {
                    "false"
                }
            });
            getImagesRequest.Filters.Add(new Amazon.EC2.Model.Filter
            {
                Name   = "owner-id",
                Values = new List <string>()
                {
                    accountId
                }
            });

            var lcResponse     = asClient.DescribeLaunchConfigurationsAsync(getLCRequest);
            var imagesResponse = ec2Client.DescribeImagesAsync(getImagesRequest);

            imagesResponse.Wait();
            lcResponse.Wait();
            imagesResponse.Result.Images.Sort((image1, image2) => - 1 * image1.CreationDate.CompareTo(image2.CreationDate));
            List <LaunchConfiguration> launchConfigIds = lcResponse.Result.LaunchConfigurations;

            var sb = new StringBuilder();

            sb.Append("DateCreated,AMI-Name,AMI-ID,OwnerID,LaunchConfigExists,LaunchConfigName,Description\n");
            imagesResponse.Result.Images.ForEach(i => {
                List <String> lcs = launchConfigIds.FindAll(lc => lc.ImageId.Equals(i.ImageId)).Select(lc => lc.LaunchConfigurationName).ToList();
                bool lcExists     = lcs.Count > 0;
                String sLcs       = lcExists ? String.Join(",", lcs) : String.Empty;
                sb.Append($"{i.CreationDate},{i.Name},{i.ImageId},{i.OwnerId},{lcExists},{sLcs},{i.Description}\n");
            });
            return(sb.ToString());
        }
コード例 #24
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);
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: slarsen88/CloudComputing
        private static void ListCustomAMI(AmazonEC2Client ec2Client)
        {
            DescribeImagesRequest request = new DescribeImagesRequest()
            {
                Owners = new List <string>()
                {
                    "271640224276"
                }
            };

            Console.WriteLine("My AMIs:\n-----");
            DescribeImagesResponse response = ec2Client.DescribeImages(request);

            foreach (var r in response.Images)
            {
                Console.WriteLine(r.ImageId + ", " + r.Name + ", " + r.Architecture);
            }
        }
コード例 #26
0
ファイル: ImagesService.cs プロジェクト: alex-zh/BackTester
        /// <summary>
        /// Возвращает AMI пренадлежащие текущему аккаунту
        /// </summary>
        /// <param name="endPoint">Регион расположения</param>
        /// <returns></returns>
        public async Task <IEnumerable <Image> > LoadSelfImagesAsync(RegionEndpoint endPoint)
        {
            using (var client = new AmazonEC2Client(endPoint))
            {
                var describeImagesRequest = new DescribeImagesRequest
                {
                    Owners = new List <string>()
                    {
                        "self"
                    }
                };

                //throw new InvalidOperationException();
                var result = await client.DescribeImagesAsync(describeImagesRequest);

                return(result.Images);
            }
        }
コード例 #27
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);
            }
        }
コード例 #28
0
        private static async Task DeleteAmis()
        {
            var client    = new AmazonEC2Client(RegionEndpoint.APSoutheast2);
            var asgClient = new AmazonAutoScalingClient(RegionEndpoint.APSoutheast2);

            var request = new DescribeImagesRequest();

            request.Owners.Add(ownerId);
            var images = await client.DescribeImagesAsync(request);

            var launchConfigs = await asgClient.DescribeLaunchConfigurationsAsync();

            var dateToKeepAmisFrom = new DateTime(2018, 11, 03);

            foreach (var image in images.Images.Where(x => DateTime.Parse(x.CreationDate) < dateToKeepAmisFrom))
            {
                Console.WriteLine($"Deleting Image: {image.ImageId} - {image.Name}...");
                if (!image.Tags.Any(t => t.Key == "Master"))
                {
                    if (launchConfigs.LaunchConfigurations.Any(x => x.ImageId == image.ImageId))
                    {
                        Console.WriteLine("Skipped belonging to Launch configuration.");
                    }
                    else
                    {
                        await client.DeregisterImageAsync(new DeregisterImageRequest(image.ImageId));

                        var snapshotIds = image.BlockDeviceMappings.Select(x => x.Ebs.SnapshotId);
                        foreach (var snapshotId in snapshotIds)
                        {
                            Console.WriteLine($"Deleting Snapshot {snapshotId}...");
                            await client.DeleteSnapshotAsync(new DeleteSnapshotRequest(snapshotId));
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Skipping because having Tag of Master.");
                }
            }
        }
コード例 #29
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonEC2Config config = new AmazonEC2Config();

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

            DescribeImagesResponse resp = new DescribeImagesResponse();
            DescribeImagesRequest  req  = new DescribeImagesRequest
            {
            };

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

            foreach (var obj in resp.Images)
            {
                AddObject(obj);
            }
        }
コード例 #30
0
        internal string FindWithFilters(List <Filter> filters, string filterByOwner = null)
        {
            var request = new DescribeImagesRequest();

            if (filterByOwner != null)
            {
                request.ExecutableUsers.Add(filterByOwner);
            }
            request.Filters = filters;

            var results = _client.DescribeImages(request);

            if (results.Images.Count == 0)
            {
                throw new Exception("Could not find any images matching filter");
            }
            var image = results.Images.Count > 1 ? results.Images.OrderByDescending(x => DateTime.Parse(x.CreationDate)).First() : results.Images.Single();

            Logger.Info("Found image with id {0}, dated {1}", image.ImageId, DateTime.Parse(image.CreationDate).ToString("yyyy-MM-dd"));
            return(image.ImageId);
        }