Пример #1
0
        internal virtual PutReportDefinitionResponse PutReportDefinition(PutReportDefinitionRequest request)
        {
            var marshaller   = PutReportDefinitionRequestMarshaller.Instance;
            var unmarshaller = PutReportDefinitionResponseUnmarshaller.Instance;

            return(Invoke <PutReportDefinitionRequest, PutReportDefinitionResponse>(request, marshaller, unmarshaller));
        }
Пример #2
0
        /// <summary>
        /// Create a new report definition
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the PutReportDefinition service method.</param>
        ///
        /// <returns>The response from the PutReportDefinition service method, as returned by CostAndUsageReport.</returns>
        /// <exception cref="Amazon.CostAndUsageReport.Model.DuplicateReportNameException">
        /// This exception is thrown when putting a report preference with a name that already
        /// exists.
        /// </exception>
        /// <exception cref="Amazon.CostAndUsageReport.Model.InternalErrorException">
        /// This exception is thrown on a known dependency failure.
        /// </exception>
        /// <exception cref="Amazon.CostAndUsageReport.Model.ReportLimitReachedException">
        /// This exception is thrown when the number of report preference reaches max limit. The
        /// max number is 5.
        /// </exception>
        /// <exception cref="Amazon.CostAndUsageReport.Model.ValidationException">
        /// This exception is thrown when providing an invalid input. eg. Put a report preference
        /// with an invalid report name, or Delete a report preference with an empty report name.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cur-2017-01-06/PutReportDefinition">REST API Reference for PutReportDefinition Operation</seealso>
        public PutReportDefinitionResponse PutReportDefinition(PutReportDefinitionRequest request)
        {
            var marshaller   = new PutReportDefinitionRequestMarshaller();
            var unmarshaller = PutReportDefinitionResponseUnmarshaller.Instance;

            return(Invoke <PutReportDefinitionRequest, PutReportDefinitionResponse>(request, marshaller, unmarshaller));
        }
Пример #3
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutReportDefinition operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutReportDefinition 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/cur-2017-01-06/PutReportDefinition">REST API Reference for PutReportDefinition Operation</seealso>
        public Task <PutReportDefinitionResponse> PutReportDefinitionAsync(PutReportDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new PutReportDefinitionRequestMarshaller();
            var unmarshaller = PutReportDefinitionResponseUnmarshaller.Instance;

            return(InvokeAsync <PutReportDefinitionRequest, PutReportDefinitionResponse>(request, marshaller,
                                                                                         unmarshaller, cancellationToken));
        }
Пример #4
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutReportDefinition operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutReportDefinition operation on AmazonCostAndUsageReportClient.</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 EndPutReportDefinition
        ///         operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cur-2017-01-06/PutReportDefinition">REST API Reference for PutReportDefinition Operation</seealso>
        public virtual IAsyncResult BeginPutReportDefinition(PutReportDefinitionRequest request, AsyncCallback callback, object state)
        {
            var marshaller   = PutReportDefinitionRequestMarshaller.Instance;
            var unmarshaller = PutReportDefinitionResponseUnmarshaller.Instance;

            return(BeginInvoke <PutReportDefinitionRequest>(request, marshaller, unmarshaller,
                                                            callback, state));
        }
 /// <summary>
 /// Creates a new report using the description that you provide.
 /// </summary>
 /// <param name="request">Container for the necessary parameters to execute the PutReportDefinition service method.</param>
 /// <param name="cancellationToken">
 ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
 /// </param>
 /// 
 /// <returns>The response from the PutReportDefinition service method, as returned by CostAndUsageReport.</returns>
 /// <exception cref="Amazon.CostAndUsageReport.Model.DuplicateReportNameException">
 /// A report with the specified name already exists in the account. Specify a different
 /// report name.
 /// </exception>
 /// <exception cref="Amazon.CostAndUsageReport.Model.InternalErrorException">
 /// An error on the server occurred during the processing of your request. Try again later.
 /// </exception>
 /// <exception cref="Amazon.CostAndUsageReport.Model.ReportLimitReachedException">
 /// This account already has five reports defined. To define a new report, you must delete
 /// an existing report.
 /// </exception>
 /// <exception cref="Amazon.CostAndUsageReport.Model.ValidationException">
 /// The input fails to satisfy the constraints specified by an AWS service.
 /// </exception>
 /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cur-2017-01-06/PutReportDefinition">REST API Reference for PutReportDefinition Operation</seealso>
 public virtual Task<PutReportDefinitionResponse> PutReportDefinitionAsync(PutReportDefinitionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
 {
     var options = new InvokeOptions();
     options.RequestMarshaller = PutReportDefinitionRequestMarshaller.Instance;
     options.ResponseUnmarshaller = PutReportDefinitionResponseUnmarshaller.Instance;
     
     return InvokeAsync<PutReportDefinitionResponse>(request, options, cancellationToken);
 }
        /// <summary>
        /// Creates a new report using the description that you provide.
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the PutReportDefinition service method.</param>
        /// 
        /// <returns>The response from the PutReportDefinition service method, as returned by CostAndUsageReport.</returns>
        /// <exception cref="Amazon.CostAndUsageReport.Model.DuplicateReportNameException">
        /// A report with the specified name already exists in the account. Specify a different
        /// report name.
        /// </exception>
        /// <exception cref="Amazon.CostAndUsageReport.Model.InternalErrorException">
        /// An error on the server occurred during the processing of your request. Try again later.
        /// </exception>
        /// <exception cref="Amazon.CostAndUsageReport.Model.ReportLimitReachedException">
        /// This account already has five reports defined. To define a new report, you must delete
        /// an existing report.
        /// </exception>
        /// <exception cref="Amazon.CostAndUsageReport.Model.ValidationException">
        /// The input fails to satisfy the constraints specified by an AWS service.
        /// </exception>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cur-2017-01-06/PutReportDefinition">REST API Reference for PutReportDefinition Operation</seealso>
        public virtual PutReportDefinitionResponse PutReportDefinition(PutReportDefinitionRequest request)
        {
            var options = new InvokeOptions();
            options.RequestMarshaller = PutReportDefinitionRequestMarshaller.Instance;
            options.ResponseUnmarshaller = PutReportDefinitionResponseUnmarshaller.Instance;

            return Invoke<PutReportDefinitionResponse>(request, options);
        }
        /// <summary>
        /// Initiates the asynchronous execution of the PutReportDefinition operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutReportDefinition operation on AmazonCostAndUsageReportClient.</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 EndPutReportDefinition
        ///         operation.</returns>
        /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/cur-2017-01-06/PutReportDefinition">REST API Reference for PutReportDefinition Operation</seealso>
        public virtual IAsyncResult BeginPutReportDefinition(PutReportDefinitionRequest request, AsyncCallback callback, object state)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = PutReportDefinitionRequestMarshaller.Instance;
            options.ResponseUnmarshaller = PutReportDefinitionResponseUnmarshaller.Instance;

            return(BeginInvoke(request, options, callback, state));
        }
Пример #8
0
        private static string GenerateUpdateJson(string oldReportName, string newReportName)
        {
            PutReportDefinitionRequest OldReportRequest = new PutReportDefinitionRequest()
            {
                ReportDefinition = new ReportDefinition()
                {
                    Compression = CompressionFormat.GZIP,
                    Format      = ReportFormat.TextORcsv,
                    S3Bucket    = OutputBucket,
                    S3Prefix    = $"{AccountNumber}/",
                    S3Region    = Region,
                    TimeUnit    = TimeUnit.DAILY,
                    ReportName  = oldReportName
                }
            };

            PutReportDefinitionRequest NewReportRequest = new PutReportDefinitionRequest()
            {
                ReportDefinition = new ReportDefinition()
                {
                    Compression = CompressionFormat.GZIP,
                    Format      = ReportFormat.TextORcsv,
                    S3Bucket    = OutputBucket,
                    S3Prefix    = $"{AccountNumber}/",
                    S3Region    = Region,
                    TimeUnit    = TimeUnit.DAILY,
                    ReportName  = newReportName
                }
            };

            GetPreSignedUrlRequest Req = new GetPreSignedUrlRequest()
            {
                BucketName = PresignedUrlBucket,
                Key        = "result.txt",
                Expires    = DateTime.Now.AddMinutes(2),
                Protocol   = Protocol.HTTPS,
                Verb       = HttpVerb.PUT
            };

            string PreSignedUrl = S3Client.GetPreSignedURL(Req);
            string Json         = $@"
{{
""requestType"":""update"",
""responseUrl"":""{PreSignedUrl}"",
""stackId"":""arn:aws:cloudformation:{Region}:{AccountNumber}:stack/stack-name/{Guid.NewGuid().ToString()}"",
""requestId"":""12345678"",
""resourceType"":""Custom::TestResource"",
""logicalResourceId"":""{oldReportName}"",
""physicalResourceId"":""{oldReportName}"",
""resourceProperties"":{JsonConvert.SerializeObject(NewReportRequest)},
""oldResourceProperties"":{JsonConvert.SerializeObject(OldReportRequest)}
}}";

            Json = Json.Trim().Replace("\r", "").Replace("\n", "").Replace("\t", "");

            return(Json);
        }
Пример #9
0
        private static string GenerateCreateJsonParquet(string reportName)
        {
            PutReportDefinitionRequest ReportRequest = new PutReportDefinitionRequest()
            {
                ReportDefinition = new ReportDefinition()
                {
                    Compression         = CompressionFormat.Parquet,
                    Format              = ReportFormat.Parquet,
                    S3Bucket            = OutputBucket,
                    S3Prefix            = $"{AccountNumber}/",
                    S3Region            = Region,
                    TimeUnit            = TimeUnit.DAILY,
                    AdditionalArtifacts = new List <string>()
                    {
                        "ATHENA"
                    },
                    AdditionalSchemaElements = new List <string>()
                    {
                        "RESOURCES"
                    }
                }
            };

            GetPreSignedUrlRequest Req = new GetPreSignedUrlRequest()
            {
                BucketName = PresignedUrlBucket,
                Key        = "result.txt",
                Expires    = DateTime.Now.AddMinutes(2),
                Protocol   = Protocol.HTTPS,
                Verb       = HttpVerb.PUT
            };

            string PreSignedUrl = S3Client.GetPreSignedURL(Req);
            string Json         = $@"
{{
""requestType"":""create"",
""responseUrl"":""{PreSignedUrl}"",
""stackId"":""arn:aws:cloudformation:{Region}:{AccountNumber}:stack/stack-name/{Guid.NewGuid().ToString()}"",
""requestId"":""12345678"",
""resourceType"":""Custom::TestResource"",
""logicalResourceId"":""{reportName}"",
""resourceProperties"":{JsonConvert.SerializeObject(ReportRequest)}
}}";

            Json = Json.Trim().Replace("\r", "").Replace("\n", "").Replace("\t", "");

            return(Json);
        }
Пример #10
0
        /// <summary>
        /// Creates a new report using the description that you provide.
        /// PutReportDefinition /#X-Amz-Target=AWSOrigamiServiceGatewayService.PutReportDefinition
        /// </summary>
        /// <returns>Success</returns>
        public async Task <PutReportDefinitionResponse> PutReportDefinitionAsync(PutReportDefinitionRequest requestBody, Action <System.Net.Http.Headers.HttpRequestHeaders> handleHeaders = null)
        {
            var requestUri = "/#X-Amz-Target=AWSOrigamiServiceGatewayService.PutReportDefinition";

            using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
            {
                using (var requestWriter = new System.IO.StringWriter())
                {
                    var requestSerializer = JsonSerializer.Create(jsonSerializerSettings);
                    requestSerializer.Serialize(requestWriter, requestBody);
                    var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json");
                    request.Content = content;
                    if (handleHeaders != null)
                    {
                        handleHeaders(request.Headers);
                    }

                    var responseMessage = await client.SendAsync(request);

                    try
                    {
                        responseMessage.EnsureSuccessStatusCodeEx();
                        var stream = await responseMessage.Content.ReadAsStreamAsync();

                        using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)))
                        {
                            var serializer = new JsonSerializer();
                            return(serializer.Deserialize <PutReportDefinitionResponse>(jsonReader));
                        }
                    }
                    finally
                    {
                        responseMessage.Dispose();
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Default constructor that Lambda will invoke.
        /// </summary>
        public Entrypoint()
        {
            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > CreateAsync = async(request, context) =>
            {
                string ReportName = String.Empty;

                try
                {
                    //arn:aws:lambda:us-east-1:123456789012:function:FunctionName
                    string[] Parts     = context.InvokedFunctionArn.Split(":");
                    string   Region    = Parts[3];
                    string   AccountId = Parts[4];

                    AmazonCostAndUsageReportConfig Config = new AmazonCostAndUsageReportConfig();
                    IAmazonCostAndUsageReport      Client = new AmazonCostAndUsageReportClient(Config);

                    PutReportDefinitionRequest Request = JsonConvert.DeserializeObject <PutReportDefinitionRequest>(JsonConvert.SerializeObject(request.ResourceProperties));

                    if (String.IsNullOrEmpty(Request.ReportDefinition.ReportName))
                    {
                        Request.ReportDefinition.ReportName = request.LogicalResourceId;
                    }

                    ReportName = Request.ReportDefinition.ReportName;

                    if (Request.ReportDefinition.AdditionalSchemaElements == null)
                    {
                        Request.ReportDefinition.AdditionalSchemaElements = new List <string>();
                    }

                    // This is required to prevent this error: Value null at 'reportDefinition.additionalSchemaElements' failed to satisfy constraint: Member must not be null
                    if (!Request.ReportDefinition.AdditionalSchemaElements.Contains("RESOURCES"))
                    {
                        Request.ReportDefinition.AdditionalSchemaElements.Add("RESOURCES");
                    }

                    // Setup defaults for the definition
                    if (String.IsNullOrEmpty(Request.ReportDefinition.S3Region))
                    {
                        Request.ReportDefinition.S3Region = Region;
                    }

                    if (Request.ReportDefinition.TimeUnit == null || String.IsNullOrEmpty(Request.ReportDefinition.TimeUnit.Value))
                    {
                        Request.ReportDefinition.TimeUnit = DefaultTimeUnit;
                    }

                    if (Request.ReportDefinition.AdditionalArtifacts != null &&
                        Request.ReportDefinition.AdditionalArtifacts.Any(x => x.Equals("ATHENA", StringComparison.OrdinalIgnoreCase))
                        )
                    {
                        if (Request.ReportDefinition.AdditionalArtifacts.Count > 1)
                        {
                            throw new InvalidOperationException("The additional artifact ATHENA cannot be combined with other values.");
                        }

                        if (Request.ReportDefinition.Format != ReportFormat.Parquet || Request.ReportDefinition.Compression != CompressionFormat.Parquet)
                        {
                            throw new InvalidOperationException("You must specify Parquet as the format and compression type when ATHENA is specified as the additional artifact.");
                        }
                    }
                    else if (Request.ReportDefinition.AdditionalArtifacts.Any(x => x.Equals("REDSHIFT", StringComparison.OrdinalIgnoreCase) || x.Equals("QUICKSIGHT", StringComparison.OrdinalIgnoreCase)))
                    {
                        if (Request.ReportDefinition.Format != ReportFormat.TextORcsv || Request.ReportDefinition.Compression != CompressionFormat.GZIP)
                        {
                            throw new InvalidOperationException("You must specify TextORCsv as the format and GZIP as the compression type when REDSHIFT or QUICKSIGHT are specified as the additional artifacts.");
                        }
                    }
                    else
                    {
                        if (Request.ReportDefinition.Compression == null || String.IsNullOrEmpty(Request.ReportDefinition.Compression.Value))
                        {
                            Request.ReportDefinition.Compression = DefaultCompression;
                        }

                        if (Request.ReportDefinition.Format == null || String.IsNullOrEmpty(Request.ReportDefinition.Format.Value))
                        {
                            Request.ReportDefinition.Format = DefaultFormat;
                        }
                    }

                    PutReportDefinitionResponse Response = await Client.PutReportDefinitionAsync(Request);

                    if ((int)Response.HttpStatusCode < 200 || (int)Response.HttpStatusCode > 299)
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.FAILED,
                                   $"Received HTTP status code {(int)Response.HttpStatusCode}.",
                                   request
                                   ));
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                   Request.ReportDefinition.ReportName,
                                   request.StackId,
                                   request.RequestId,
                                   request.LogicalResourceId,
                                   false,
                                   new Dictionary <string, object>()
                        {
                            { "Name", Request.ReportDefinition.ReportName },
                            { "Arn", $"arn:aws:cur:{Region}:{AccountId}:definition/{ReportName}" },
                            { "Id", Request.ReportDefinition.ReportName }
                        }
                                   ));
                    }
                }
                catch (AmazonCostAndUsageReportException e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               ReportName,
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
                catch (Exception e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               ReportName,
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
            };

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > DeleteAsync = async(request, context) =>
            {
                try
                {
                    //arn:aws:lambda:us-east-1:123456789012:function:FunctionName
                    string[] Parts     = context.InvokedFunctionArn.Split(":");
                    string   Region    = Parts[3];
                    string   AccountId = Parts[4];

                    AmazonCostAndUsageReportConfig Config = new AmazonCostAndUsageReportConfig();
                    IAmazonCostAndUsageReport      Client = new AmazonCostAndUsageReportClient(Config);

                    DeleteReportDefinitionRequest Request = new DeleteReportDefinitionRequest()
                    {
                        ReportName = request.PhysicalResourceId
                    };

                    DeleteReportDefinitionResponse Response = await Client.DeleteReportDefinitionAsync(Request);

                    if ((int)Response.HttpStatusCode < 200 || (int)Response.HttpStatusCode > 299)
                    {
                        return(new CustomResourceResponse(CustomResourceResponse.RequestStatus.FAILED, $"Received HTTP status code {(int)Response.HttpStatusCode}.", request));
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                   request.PhysicalResourceId,
                                   request.StackId,
                                   request.RequestId,
                                   request.LogicalResourceId,
                                   false,
                                   new Dictionary <string, object>()
                        {
                            { "Name", request.PhysicalResourceId as string },
                            { "Arn", $"arn:aws:cur:{Region}:{AccountId}:definition/{request.PhysicalResourceId}" },
                            { "Id", request.PhysicalResourceId as string }
                        }
                                   ));
                    }
                }
                catch (AmazonCostAndUsageReportException e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request.PhysicalResourceId,
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
                catch (Exception e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request.PhysicalResourceId,
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
            };

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > UpdateAsync = async(request, context) =>
            {
                CustomResourceResponse Response = await DeleteAsync(request, context);

                if (Response.Status == CustomResourceResponse.RequestStatus.SUCCESS)
                {
                    return(await CreateAsync(request, context));
                }
                else
                {
                    return(Response);
                }
            };

            this._Handler = new CustomResourceFactory(CreateAsync, UpdateAsync, DeleteAsync);

            this.ProcessEnvironmentVariables();
        }