internal CreateFunctionResponse CreateFunction(CreateFunctionRequest request) { var marshaller = new CreateFunctionRequestMarshaller(); var unmarshaller = CreateFunctionResponseUnmarshaller.Instance; return(Invoke <CreateFunctionRequest, CreateFunctionResponse>(request, marshaller, unmarshaller)); }
/// <summary> /// Creates a new function. /// </summary> /// <param name="request">The request object containing the details to send. Required.</param> /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param> /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param> /// <returns>A response object containing details about the completed operation</returns> /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/functions/CreateFunction.cs.html">here</a> to see an example of how to use CreateFunction API.</example> public async Task <CreateFunctionResponse> CreateFunction(CreateFunctionRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called createFunction"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/functions".Trim('/'))); HttpMethod method = new HttpMethod("POST"); HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request); requestMessage.Headers.Add("Accept", "application/json"); GenericRetrier retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration); HttpResponseMessage responseMessage; try { if (retryingClient != null) { responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false); } else { responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false); } this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage); return(Converter.FromHttpResponseMessage <CreateFunctionResponse>(responseMessage)); } catch (Exception e) { logger.Error($"CreateFunction failed with error: {e.Message}"); throw; } }
/** * Creates a Function and waits for the it to become available to use. * * @param fnManagementClient the service client to use to create the Application. * @param applicationId the OCID of the Application which owns the Function. * @param displayName the display name of created Function. * @param image an accessible OCI Registry image implementing the function to be executed. * @param memoryInMBs the maximum amount of memory available (128, 256, 512, 1024) to the function in MB. * @param timeoutInSeconds the maximum amount of time a function can execute (30 - 120) in seconds. * @return the created Function. */ private static async Task <Function> CreateFunction(FunctionsManagementClient fnManagementClient, string applicationId, string image, long memoryInMBs, int timeoutInSeconds) { logger.Info("Creating function"); // Create a new function var createFunctionDetails = new CreateFunctionDetails { ApplicationId = applicationId, DisplayName = FunctionName, Image = image, MemoryInMBs = memoryInMBs, TimeoutInSeconds = timeoutInSeconds }; var createFunctionRequest = new CreateFunctionRequest { CreateFunctionDetails = createFunctionDetails }; var createFunctionResponse = await fnManagementClient.CreateFunction(createFunctionRequest); logger.Info("Waiting for Function to be in Active state"); var getFunctionRequest = new GetFunctionRequest { FunctionId = createFunctionResponse.Function.Id }; var getFunctionResponse = fnManagementClient.Waiters.ForFunction(getFunctionRequest, Function.LifecycleStateEnum.Active).Execute(); logger.Info($"Function: {FunctionName} is Active"); return(getFunctionResponse.Function); }
/// <summary>Snippet for CreateFunctionAsync</summary> public async Task CreateFunctionRequestObjectAsync() { // Snippet: CreateFunctionAsync(CreateFunctionRequest, CallSettings) // Additional: CreateFunctionAsync(CreateFunctionRequest, CancellationToken) // Create client CloudFunctionsServiceClient cloudFunctionsServiceClient = await CloudFunctionsServiceClient.CreateAsync(); // Initialize request argument(s) CreateFunctionRequest request = new CreateFunctionRequest { LocationAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Function = new CloudFunction(), }; // Make the request Operation <CloudFunction, OperationMetadataV1> response = await cloudFunctionsServiceClient.CreateFunctionAsync(request); // Poll until the returned long-running operation is complete Operation <CloudFunction, OperationMetadataV1> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result CloudFunction result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation <CloudFunction, OperationMetadataV1> retrievedResponse = await cloudFunctionsServiceClient.PollOnceCreateFunctionAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result CloudFunction retrievedResult = retrievedResponse.Result; } // End snippet }
public async Task With_lambda_service_and_LAMBDA_FORWARD_URL_then_should_invoke() { await using var fixture = await LocalStackFixture.Create(_outputHelper); // 1. Arrange: Create dummy lambda function in localstack var functionInfo = fixture.LambdaTestHost.Settings.Functions.First().Value; var createFunctionRequest = new CreateFunctionRequest { Handler = "dummy-handler", // ignored FunctionName = functionInfo.Name, // must match Role = "arn:aws:iam::123456789012:role/foo", // must be specified Code = new FunctionCode { ZipFile = new MemoryStream() // must be specified but is ignored } }; await fixture.LambdaClient.CreateFunctionAsync(createFunctionRequest); // 2. Act: Call lambda Invoke API var invokeRequest = new InvokeRequest { FunctionName = functionInfo.Name, Payload = "{\"Data\":\"Bar\"}", }; var invokeResponse = await fixture.LambdaClient.InvokeAsync(invokeRequest); // 3. Assert: Check payload was forwarded invokeResponse.HttpStatusCode.ShouldBe(HttpStatusCode.OK); invokeResponse.FunctionError.ShouldBeNullOrEmpty(); var responsePayload = Encoding.UTF8.GetString(invokeResponse.Payload.ToArray()); responsePayload.ShouldStartWith("{\"Reverse\":\"raB\"}"); }
/// <summary> /// Initiates the asynchronous execution of the CreateFunction operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateFunction 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 <CreateFunctionResponse> CreateFunctionAsync(CreateFunctionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateFunctionRequestMarshaller(); var unmarshaller = CreateFunctionResponseUnmarshaller.Instance; return(InvokeAsync <CreateFunctionRequest, CreateFunctionResponse>(request, marshaller, unmarshaller, cancellationToken)); }
/// <summary> /// 创建函数。 /// </summary> public async Task <CreateFunctionResponse> CreateFunctionAsync(CreateFunctionRequest createFunctionRequest) { Dictionary <string, string> urlParam = new Dictionary <string, string>(); string urlPath = HttpUtils.AddUrlPath("/v2/{project_id}/fgs/functions", urlParam); SdkRequest request = HttpUtils.InitSdkRequest(urlPath, "application/json", createFunctionRequest); HttpResponseMessage response = await DoHttpRequestAsync("POST", request); return(JsonUtils.DeSerialize <CreateFunctionResponse>(response)); }
public static void CreateLambdaFunction(string functionName, string iamRoleName, out string iamRoleArn, out string functionArn) { var iamCreateResponse = iamClient.CreateRole(new CreateRoleRequest { RoleName = iamRoleName, AssumeRolePolicyDocument = LAMBDA_ASSUME_ROLE_POLICY }); iamRoleArn = iamCreateResponse.Role.Arn; var statement = new Statement(Statement.StatementEffect.Allow); statement.Actions.Add(S3ActionIdentifiers.PutObject); statement.Actions.Add(S3ActionIdentifiers.GetObject); statement.Resources.Add(new Resource("*")); var policy = new Amazon.Auth.AccessControlPolicy.Policy(); policy.Statements.Add(statement); iamClient.PutRolePolicy(new PutRolePolicyRequest { RoleName = iamRoleName, PolicyName = "admin", PolicyDocument = policy.ToJson() }); // Wait for the role and policy to propagate Thread.Sleep(5000); MemoryStream stream = CreateScriptStream(); var uploadRequest = new CreateFunctionRequest { FunctionName = functionName, Code = new FunctionCode { ZipFile = stream }, Handler = "helloworld.handler", //Mode = Mode.Event, Runtime = Runtime.Nodejs, Role = iamCreateResponse.Role.Arn }; var uploadResponse = Client.CreateFunction(uploadRequest); createdFunctionNames.Add(functionName); Assert.IsTrue(uploadResponse.CodeSize > 0); Assert.IsNotNull(uploadResponse.FunctionArn); functionArn = uploadResponse.FunctionArn; }
internal static async Task <CreateFunctionResponse> CreateFunctionAsync ( this AmazonLambdaClient client, AppPackage package, ASPNetServerLessPublishAWSLambdaConfigSection lambdaConfig, Runtime lambdaRuntime, CancellationToken cancellationToken = default(CancellationToken) ) { var environmentVariables = new Dictionary <string, string>(lambdaConfig.EnvironmentVAriables); var functionTags = new Dictionary <string, string> { { "Name", lambdaConfig.FunctionName } }; var response = (CreateFunctionResponse)null; using (var packageStream = new MemoryStream(package.PackageBytes)) { var createFunctionRequest = new CreateFunctionRequest() { Code = new FunctionCode() { ZipFile = packageStream }, Environment = new Environment() { Variables = environmentVariables }, FunctionName = lambdaConfig.FunctionName, Handler = lambdaConfig.FunctionHandler, MemorySize = lambdaConfig.FunctionMemory.Value, Role = lambdaConfig.FunctionRole, Tags = functionTags, Timeout = lambdaConfig.FunctionTimeoutSeconds.Value, Runtime = lambdaRuntime }; response = await client.CreateFunctionAsync(createFunctionRequest, cancellationToken).ConfigureAwait(false); createFunctionRequest = null; } functionTags = null; environmentVariables = null; return(response); }
protected async Task CreateFunctionAsync(IAmazonLambda lambdaClient, string bucketName) { await DeleteFunctionIfExistsAsync(lambdaClient); var createRequest = new CreateFunctionRequest { FunctionName = FunctionName, Code = new FunctionCode { S3Bucket = bucketName, S3Key = DeploymentZipKey }, Handler = "PingAsync", MemorySize = 512, Timeout = 30, Runtime = Runtime.ProvidedAl2, Role = ExecutionRoleArn }; var startTime = DateTime.Now; var created = false; while (DateTime.Now < startTime.AddSeconds(30)) { try { await lambdaClient.CreateFunctionAsync(createRequest); created = true; break; } catch (InvalidParameterValueException ipve) { // Wait for the role to be fully propagated through AWS if (ipve.Message == "The role defined for the function cannot be assumed by Lambda.") { await Task.Delay(2000); } else { throw; } } } await Task.Delay(5000); if (!created) { throw new Exception($"Timed out trying to create Lambda function {FunctionName}"); } }
/// <summary> /// CreateFunction接口的同步版本,该接口根据传入参数创建新的函数。 /// </summary> /// <param name="req">参考<see cref="CreateFunctionRequest"/></param> /// <returns>参考<see cref="CreateFunctionResponse"/>实例</returns> public CreateFunctionResponse CreateFunctionSync(CreateFunctionRequest req) { JsonResponseModel <CreateFunctionResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "CreateFunction"); rsp = JsonConvert.DeserializeObject <JsonResponseModel <CreateFunctionResponse> >(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return(rsp.Response); }
/// <summary> /// 创建函数 /// </summary> public static void CreateFunction(FunctionGraphClient client) { CreateFunctionRequest req = new CreateFunctionRequest { Body = new CreateFunctionRequestBody { FuncName = "csharpSdkTest", Handler = "index.handler", MemorySize = 128, Timeout = 3, Runtime = CreateFunctionRequestBody.RuntimeEnum.NODE_JS6_10, Package = "CsharpSdkTest", CodeType = CreateFunctionRequestBody.CodeTypeEnum.INLINE, CodeFilename = "index.zip", FuncCode = new FuncCode { File = "UEsDBAoAAAAAAHYLfU2fZFKzsAAAALAAAAAIAAAAaW5kZXguanNleHBvcnRzLmhhbmRsZXIgPSBmdW5jdGlvbiAoZXZlbnQsIGNvbnRleHQsIGNhbGxiYWNrKSB7DQogICAgY29uc3QgZXJyb3IgPSBudWxsOw0KICAgIGNvbnN0IG91dHB1dCA9IGBIZWxsbyBtZXNzYWdlOiAke0pTT04uc3RyaW5naWZ5KGV2ZW50KX1gOw0KICAgIGNhbGxiYWNrKGVycm9yLCBvdXRwdXQpOw0KfVBLAQIeAwoAAAAAAHYLfU2fZFKzsAAAALAAAAAIAAAAAAAAAAAAAAC0gQAAAABpbmRleC5qc1BLBQYAAAAAAQABADYAAADWAAAAAAA=" } } }; try { CreateFunctionResponse resp = client.CreateFunction(req); Console.WriteLine("Create Function Body=" + JsonConvert.SerializeObject(resp)); Console.WriteLine("func_name=" + resp.FuncName); Console.WriteLine("func_urn=" + resp.FuncUrn); Console.WriteLine("Create Function StatusCode=" + resp.HttpStatusCode); } catch (ClientRequestException e) { Console.WriteLine(e.HttpStatusCode); Console.WriteLine(e.ErrorCode); Console.WriteLine(e.ErrorMsg); } catch (ConnectionException e) { Console.WriteLine(e.ErrorMessage); } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// Initiates the asynchronous execution of the CreateFunction operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateFunction operation on AmazonLambdaClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">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> public void CreateFunctionAsync(CreateFunctionRequest request, AmazonServiceCallback <CreateFunctionRequest, CreateFunctionResponse> callback, AsyncOptions options = null) { options = options == null?new AsyncOptions():options; var marshaller = new CreateFunctionRequestMarshaller(); var unmarshaller = CreateFunctionResponseUnmarshaller.Instance; Action <AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null; if (callback != null) { callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { AmazonServiceResult <CreateFunctionRequest, CreateFunctionResponse> responseObject = new AmazonServiceResult <CreateFunctionRequest, CreateFunctionResponse>((CreateFunctionRequest)req, (CreateFunctionResponse)res, ex, ao.State); callback(responseObject); } } ; BeginInvoke <CreateFunctionRequest>(request, marshaller, unmarshaller, options, callbackHelper); }
protected override void ProcessRecord() { base.ProcessRecord(); CreateFunctionRequest request; try { request = new CreateFunctionRequest { CreateFunctionDetails = CreateFunctionDetails, OpcRequestId = OpcRequestId }; response = client.CreateFunction(request).GetAwaiter().GetResult(); WriteOutput(response, response.Function); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
public async Task Should_invoke_with_sqs_event_source_mapping() { await using var fixture = await LocalStackFixture.Create(_outputHelper); // 1.1 Arrange: Create dummy lambda function in localstack var functionInfo = fixture.LambdaTestHost.Settings.Functions.Last().Value; var createFunctionRequest = new CreateFunctionRequest { Handler = "dummy-handler", // ignored FunctionName = functionInfo.Name, // must match Role = "arn:aws:iam::123456789012:role/foo", // must be specified Code = new FunctionCode { ZipFile = new MemoryStream() // must be specified but is ignored } }; await fixture.LambdaClient.CreateFunctionAsync(createFunctionRequest); // 1.2 Arrange: Create queue and event source mapping var queueName = "test-queue"; var createQueueResponse = await fixture.SQSClient.CreateQueueAsync(queueName); var createEventSourceMappingRequest = new CreateEventSourceMappingRequest { FunctionName = functionInfo.Name, EventSourceArn = $"arn:aws:sqs:eu-west-1:123456789012:{queueName}", BatchSize = 1, Enabled = true, }; var createEventSourceMappingResponse = await fixture.LambdaClient.CreateEventSourceMappingAsync(createEventSourceMappingRequest); // 2. Act: send message to queue await fixture.SQSClient.SendMessageAsync(createQueueResponse.QueueUrl, "hello"); await Task.Delay(10000); }
public override async Task <bool> ExecuteAsync() { try { string projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, DefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); string zipArchivePath = null; string publishLocation = null; string package = this.GetStringValueOrDefault(this.Package, DefinedCommandOptions.ARGUMENT_PACKAGE, false); if (string.IsNullOrEmpty(package)) { string configuration = this.GetStringValueOrDefault(this.Configuration, DefinedCommandOptions.ARGUMENT_CONFIGURATION, true); string targetFramework = this.GetStringValueOrDefault(this.TargetFramework, DefinedCommandOptions.ARGUMENT_FRAMEWORK, true); ValidateTargetFrameworkAndLambdaRuntime(); LambdaPackager.CreateApplicationBundle(this.DefaultConfig, this.Logger, this.WorkingDirectory, projectLocation, configuration, targetFramework, out publishLocation, ref zipArchivePath); if (string.IsNullOrEmpty(zipArchivePath)) { return(false); } } else { if (!File.Exists(package)) { throw new LambdaToolsException($"Package {package} does not exist", LambdaToolsException.ErrorCode.InvalidPackage); } if (!string.Equals(Path.GetExtension(package), ".zip", StringComparison.OrdinalIgnoreCase)) { throw new LambdaToolsException($"Package {package} must be a zip file", LambdaToolsException.ErrorCode.InvalidPackage); } this.Logger.WriteLine($"Skipping compilation and using precompiled package {package}"); zipArchivePath = package; } using (var stream = new MemoryStream(File.ReadAllBytes(zipArchivePath))) { var s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, DefinedCommandOptions.ARGUMENT_S3_BUCKET, false); string s3Key = null; if (!string.IsNullOrEmpty(s3Bucket)) { await Utilities.ValidateBucketRegionAsync(this.S3Client, s3Bucket); var functionName = this.GetStringValueOrDefault(this.FunctionName, DefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true); var s3Prefix = this.GetStringValueOrDefault(this.S3Prefix, DefinedCommandOptions.ARGUMENT_S3_PREFIX, false); s3Key = await Utilities.UploadToS3Async(this.Logger, this.S3Client, s3Bucket, s3Prefix, functionName, stream); } var currentConfiguration = await GetFunctionConfigurationAsync(); if (currentConfiguration == null) { this.Logger.WriteLine($"Creating new Lambda function {this.FunctionName}"); var createRequest = new CreateFunctionRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, DefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true), Description = this.GetStringValueOrDefault(this.Description, DefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, false), Role = this.GetStringValueOrDefault(this.Role, DefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, true), Handler = this.GetStringValueOrDefault(this.Handler, DefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, true), Publish = this.GetBoolValueOrDefault(this.Publish, DefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(), MemorySize = this.GetIntValueOrDefault(this.MemorySize, DefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, true).GetValueOrDefault(), Runtime = this.GetStringValueOrDefault(this.Runtime, DefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, true), Timeout = this.GetIntValueOrDefault(this.Timeout, DefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, true).GetValueOrDefault(), KMSKeyArn = this.GetStringValueOrDefault(this.KMSKeyArn, DefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, false), VpcConfig = new VpcConfig { SubnetIds = this.GetStringValuesOrDefault(this.SubnetIds, DefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, false)?.ToList(), SecurityGroupIds = this.GetStringValuesOrDefault(this.SecurityGroupIds, DefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, false)?.ToList() } }; var environmentVariables = this.GetKeyValuePairOrDefault(this.EnvironmentVariables, DefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES, false); if (environmentVariables != null && environmentVariables.Count > 0) { createRequest.Environment = new Model.Environment { Variables = environmentVariables }; } var deadLetterQueue = this.GetStringValueOrDefault(this.DeadLetterTargetArn, DefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, false); if (!string.IsNullOrEmpty(deadLetterQueue)) { createRequest.DeadLetterConfig = new DeadLetterConfig { TargetArn = deadLetterQueue }; } if (s3Bucket != null) { createRequest.Code = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key }; } else { createRequest.Code = new FunctionCode { ZipFile = stream }; } if (!this.SkipHandlerValidation && !string.IsNullOrEmpty(publishLocation)) { createRequest.Handler = EnsureFunctionHandlerIsValid(publishLocation, createRequest.Handler); } try { await this.LambdaClient.CreateFunctionAsync(createRequest); this.Logger.WriteLine("New Lambda function created"); } catch (Exception e) { throw new LambdaToolsException($"Error creating Lambda function: {e.Message}", LambdaToolsException.ErrorCode.LambdaCreateFunction, e); } } else { if (!this.SkipHandlerValidation && !string.IsNullOrEmpty(publishLocation)) { if (!string.IsNullOrEmpty(this.Handler)) { this.Handler = EnsureFunctionHandlerIsValid(publishLocation, this.Handler); } else { this.Handler = EnsureFunctionHandlerIsValid(publishLocation, currentConfiguration.Handler); } } this.Logger.WriteLine($"Updating code for existing function {this.FunctionName}"); var updateCodeRequest = new UpdateFunctionCodeRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, DefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true) }; if (s3Bucket != null) { updateCodeRequest.S3Bucket = s3Bucket; updateCodeRequest.S3Key = s3Key; } else { updateCodeRequest.ZipFile = stream; } try { await this.LambdaClient.UpdateFunctionCodeAsync(updateCodeRequest); } catch (Exception e) { throw new LambdaToolsException($"Error updating code for Lambda function: {e.Message}", LambdaToolsException.ErrorCode.LambdaUpdateFunctionCode, e); } await base.UpdateConfigAsync(currentConfiguration); } } if (this.GetBoolValueOrDefault(this.PersistConfigFile, DefinedCommandOptions.ARGUMENT_PERSIST_CONFIG_FILE, false).GetValueOrDefault()) { this.SaveConfigFile(); } return(true); } catch (LambdaToolsException e) { this.Logger.WriteLine(e.Message); this.LastToolsException = e; return(false); } catch (Exception e) { this.Logger.WriteLine($"Unknown error executing Lambda deployment: {e.Message}"); this.Logger.WriteLine(e.StackTrace); return(false); } }
protected override async Task <bool> PerformActionAsync() { string projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); string zipArchivePath = null; string package = this.GetStringValueOrDefault(this.Package, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE, false); var layerVersionArns = this.GetStringValuesOrDefault(this.LayerVersionArns, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, false); var layerPackageInfo = await LambdaUtilities.LoadLayerPackageInfos(this.Logger, this.LambdaClient, this.S3Client, layerVersionArns); Lambda.PackageType packageType = DeterminePackageType(); string ecrImageUri = null; if (packageType == Lambda.PackageType.Image) { var pushResults = await PushLambdaImageAsync(); if (!pushResults.Success) { if (pushResults.LastToolsException != null) { throw pushResults.LastToolsException; } return(false); } ecrImageUri = pushResults.ImageUri; } else { if (string.IsNullOrEmpty(package)) { EnsureInProjectDirectory(); // Release will be the default configuration if nothing set. string configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false); var targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false); if (string.IsNullOrEmpty(targetFramework)) { targetFramework = Utilities.LookupTargetFrameworkFromProjectFile(Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation)); // If we still don't know what the target framework is ask the user what targetframework to use. // This is common when a project is using multi targeting. if (string.IsNullOrEmpty(targetFramework)) { targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true); } } string msbuildParameters = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false); ValidateTargetFrameworkAndLambdaRuntime(targetFramework); bool disableVersionCheck = this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false).GetValueOrDefault(); string publishLocation; LambdaPackager.CreateApplicationBundle(this.DefaultConfig, this.Logger, this.WorkingDirectory, projectLocation, configuration, targetFramework, msbuildParameters, disableVersionCheck, layerPackageInfo, out publishLocation, ref zipArchivePath); if (string.IsNullOrEmpty(zipArchivePath)) { return(false); } } else { if (!File.Exists(package)) { throw new LambdaToolsException($"Package {package} does not exist", LambdaToolsException.LambdaErrorCode.InvalidPackage); } if (!string.Equals(Path.GetExtension(package), ".zip", StringComparison.OrdinalIgnoreCase)) { throw new LambdaToolsException($"Package {package} must be a zip file", LambdaToolsException.LambdaErrorCode.InvalidPackage); } this.Logger.WriteLine($"Skipping compilation and using precompiled package {package}"); zipArchivePath = package; } } MemoryStream lambdaZipArchiveStream = null; if (zipArchivePath != null) { lambdaZipArchiveStream = new MemoryStream(File.ReadAllBytes(zipArchivePath)); } try { var s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false); string s3Key = null; if (zipArchivePath != null && !string.IsNullOrEmpty(s3Bucket)) { await Utilities.ValidateBucketRegionAsync(this.S3Client, s3Bucket); var functionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true); var s3Prefix = this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false); s3Key = await Utilities.UploadToS3Async(this.Logger, this.S3Client, s3Bucket, s3Prefix, functionName, lambdaZipArchiveStream); } var currentConfiguration = await GetFunctionConfigurationAsync(); if (currentConfiguration == null) { this.Logger.WriteLine($"Creating new Lambda function {this.FunctionName}"); var createRequest = new CreateFunctionRequest { PackageType = packageType, FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true), Description = this.GetStringValueOrDefault(this.Description, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, false), Role = this.GetRoleValueOrDefault(this.Role, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, Constants.LAMBDA_PRINCIPAL, LambdaConstants.AWS_LAMBDA_MANAGED_POLICY_PREFIX, LambdaConstants.KNOWN_MANAGED_POLICY_DESCRIPTIONS, true), Publish = this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(), MemorySize = this.GetIntValueOrDefault(this.MemorySize, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, true).GetValueOrDefault(), Timeout = this.GetIntValueOrDefault(this.Timeout, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, true).GetValueOrDefault(), KMSKeyArn = this.GetStringValueOrDefault(this.KMSKeyArn, LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, false), VpcConfig = new VpcConfig { SubnetIds = this.GetStringValuesOrDefault(this.SubnetIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, false)?.ToList(), SecurityGroupIds = this.GetStringValuesOrDefault(this.SecurityGroupIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, false)?.ToList() } }; if (packageType == Lambda.PackageType.Zip) { createRequest.Handler = this.GetStringValueOrDefault(this.Handler, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, true); createRequest.Runtime = this.GetStringValueOrDefault(this.Runtime, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, true); createRequest.Layers = layerVersionArns?.ToList(); if (s3Bucket != null) { createRequest.Code = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key }; } else { createRequest.Code = new FunctionCode { ZipFile = lambdaZipArchiveStream }; } } else if (packageType == Lambda.PackageType.Image) { createRequest.Code = new FunctionCode { ImageUri = ecrImageUri }; createRequest.ImageConfig = new ImageConfig { Command = this.GetStringValuesOrDefault(this.ImageCommand, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND, false)?.ToList(), EntryPoint = this.GetStringValuesOrDefault(this.ImageEntryPoint, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT, false)?.ToList(), WorkingDirectory = this.GetStringValueOrDefault(this.ImageWorkingDirectory, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY, false) }; } var environmentVariables = GetEnvironmentVariables(null); var dotnetShareStoreVal = layerPackageInfo.GenerateDotnetSharedStoreValue(); if (!string.IsNullOrEmpty(dotnetShareStoreVal)) { if (environmentVariables == null) { environmentVariables = new Dictionary <string, string>(); } environmentVariables[LambdaConstants.ENV_DOTNET_SHARED_STORE] = dotnetShareStoreVal; } if (environmentVariables != null && environmentVariables.Count > 0) { createRequest.Environment = new Model.Environment { Variables = environmentVariables }; } var tags = this.GetKeyValuePairOrDefault(this.Tags, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, false); if (tags != null && tags.Count > 0) { createRequest.Tags = tags; } var deadLetterQueue = this.GetStringValueOrDefault(this.DeadLetterTargetArn, LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, false); if (!string.IsNullOrEmpty(deadLetterQueue)) { createRequest.DeadLetterConfig = new DeadLetterConfig { TargetArn = deadLetterQueue }; } var tracingMode = this.GetStringValueOrDefault(this.TracingMode, LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE, false); if (!string.IsNullOrEmpty(tracingMode)) { createRequest.TracingConfig = new TracingConfig { Mode = tracingMode }; } try { await this.LambdaClient.CreateFunctionAsync(createRequest); this.Logger.WriteLine("New Lambda function created"); } catch (Exception e) { throw new LambdaToolsException($"Error creating Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaCreateFunction, e); } } else { this.Logger.WriteLine($"Updating code for existing function {this.FunctionName}"); var updateCodeRequest = new UpdateFunctionCodeRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true) }; // In case the function is currently being updated from previous deployment wait till it available // to be updated. if (currentConfiguration.LastUpdateStatus == LastUpdateStatus.InProgress) { await LambdaUtilities.WaitTillFunctionAvailableAsync(Logger, this.LambdaClient, updateCodeRequest.FunctionName); } if (packageType == Lambda.PackageType.Zip) { if (s3Bucket != null) { updateCodeRequest.S3Bucket = s3Bucket; updateCodeRequest.S3Key = s3Key; } else { updateCodeRequest.ZipFile = lambdaZipArchiveStream; } } else if (packageType == Lambda.PackageType.Image) { updateCodeRequest.ImageUri = ecrImageUri; } try { await this.LambdaClient.UpdateFunctionCodeAsync(updateCodeRequest); } catch (Exception e) { throw new LambdaToolsException($"Error updating code for Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaUpdateFunctionCode, e); } await base.UpdateConfigAsync(currentConfiguration, layerPackageInfo.GenerateDotnetSharedStoreValue()); await base.ApplyTags(currentConfiguration.FunctionArn); var publish = this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(); if (publish) { await base.PublishFunctionAsync(updateCodeRequest.FunctionName); } } } finally { lambdaZipArchiveStream?.Dispose(); } return(true); }
public void CreateFunctionAsync(CreateFunctionRequest request, AmazonServiceCallback <CreateFunctionRequest, CreateFunctionResponse> callback, AsyncOptions options = null) { throw new System.NotImplementedException(); }
/// <summary> /// Updates the AWS Lambda functions code. /// </summary> /// <param name="functionName">The name of an AWS Lambda function.</param> /// <param name="settings">The <see cref="UpdateFunctionCodeSettings"/> used during the request to AWS.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async Task <string> CreateFunction(string functionName, CreateFunctionSettings settings, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(functionName)) { throw new ArgumentNullException(nameof(functionName)); } // Create Request AmazonLambdaClient client = this.CreateClient(settings); CreateFunctionRequest request = new CreateFunctionRequest() { FunctionName = functionName, Handler = settings.Handler, Runtime = Runtime.FindValue(settings.Runtime), Role = settings.Role, Environment = new Amazon.Lambda.Model.Environment() { Variables = settings.Environment }, Timeout = settings.Timeout, MemorySize = settings.MemorySize, Publish = settings.Publish, KMSKeyArn = settings.KMSKeyArn, Tags = settings.Tags, Description = settings.Description, Code = new FunctionCode() { S3Bucket = settings.S3Bucket, S3Key = settings.S3Key, S3ObjectVersion = settings.S3Version, } }; if (!String.IsNullOrEmpty(settings.DeadLetterConfig)) { request.DeadLetterConfig.TargetArn = settings.DeadLetterConfig; } if (settings.ZipPath != null) { request.Code.ZipFile = this.GetFileStream(settings.ZipPath, settings); } if (settings.VpcSecurityGroupIds.Count > 0) { request.VpcConfig.SecurityGroupIds = settings.VpcSecurityGroupIds; } if (settings.VpcSubnetIds.Count > 0) { request.VpcConfig.SubnetIds = settings.VpcSubnetIds; } // Check Response CreateFunctionResponse response = await client.CreateFunctionAsync(request, cancellationToken); if (response.HttpStatusCode == HttpStatusCode.OK) { _Log.Verbose("Successfully updated function '{0}'", functionName); return(response.Version); } else { _Log.Error("Failed to update function '{0}'", functionName); return(""); } }
/// <summary> /// 创建函数 /// </summary> /// <param name="request">请求参数信息</param> /// <returns>请求结果信息</returns> public CreateFunctionResponse CreateFunction(CreateFunctionRequest request) { return(new CreateFunctionExecutor().Client(this).Execute <CreateFunctionResponse, CreateFunctionResult, CreateFunctionRequest>(request)); }
/// <summary> /// 创建函数 /// </summary> /// <param name="request">请求参数信息</param> /// <returns>请求结果信息</returns> public async Task <CreateFunctionResponse> CreateFunction(CreateFunctionRequest request) { return(await new CreateFunctionExecutor().Client(this).Execute <CreateFunctionResponse, CreateFunctionResult, CreateFunctionRequest>(request).ConfigureAwait(false)); }
/// <summary> /// Creates the function. /// </summary> /// <returns>The function.</returns> /// <param name="createFunctionRequest">Create function request.</param> public CreateFunctionResponse CreateFunction(CreateFunctionRequest createFunctionRequest) { return(this.DoRequestCommon <CreateFunctionResponse>(createFunctionRequest.GenHttpRequest(Config))); }
protected override async Task <bool> PerformActionAsync() { string projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); string zipArchivePath = null; string package = this.GetStringValueOrDefault(this.Package, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE, false); if (string.IsNullOrEmpty(package)) { EnsureInProjectDirectory(); string configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, true); string targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true); string msbuildParameters = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false); ValidateTargetFrameworkAndLambdaRuntime(); bool disableVersionCheck = this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false).GetValueOrDefault(); string publishLocation; LambdaPackager.CreateApplicationBundle(this.DefaultConfig, this.Logger, this.WorkingDirectory, projectLocation, configuration, targetFramework, msbuildParameters, disableVersionCheck, out publishLocation, ref zipArchivePath); if (string.IsNullOrEmpty(zipArchivePath)) { return(false); } } else { if (!File.Exists(package)) { throw new LambdaToolsException($"Package {package} does not exist", LambdaToolsException.LambdaErrorCode.InvalidPackage); } if (!string.Equals(Path.GetExtension(package), ".zip", StringComparison.OrdinalIgnoreCase)) { throw new LambdaToolsException($"Package {package} must be a zip file", LambdaToolsException.LambdaErrorCode.InvalidPackage); } this.Logger.WriteLine($"Skipping compilation and using precompiled package {package}"); zipArchivePath = package; } using (var stream = new MemoryStream(File.ReadAllBytes(zipArchivePath))) { var s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false); string s3Key = null; if (!string.IsNullOrEmpty(s3Bucket)) { await Utilities.ValidateBucketRegionAsync(this.S3Client, s3Bucket); var functionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true); var s3Prefix = this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false); s3Key = await Utilities.UploadToS3Async(this.Logger, this.S3Client, s3Bucket, s3Prefix, functionName, stream); } var currentConfiguration = await GetFunctionConfigurationAsync(); if (currentConfiguration == null) { this.Logger.WriteLine($"Creating new Lambda function {this.FunctionName}"); var createRequest = new CreateFunctionRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true), Description = this.GetStringValueOrDefault(this.Description, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, false), Role = this.GetRoleValueOrDefault(this.Role, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, Constants.LAMBDA_PRINCIPAL, LambdaConstants.AWS_LAMBDA_MANAGED_POLICY_PREFIX, LambdaConstants.KNOWN_MANAGED_POLICY_DESCRIPTIONS, true), Handler = this.GetStringValueOrDefault(this.Handler, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, true), Publish = this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(), MemorySize = this.GetIntValueOrDefault(this.MemorySize, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, true).GetValueOrDefault(), Runtime = this.GetStringValueOrDefault(this.Runtime, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, true), Timeout = this.GetIntValueOrDefault(this.Timeout, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, true).GetValueOrDefault(), KMSKeyArn = this.GetStringValueOrDefault(this.KMSKeyArn, LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, false), VpcConfig = new VpcConfig { SubnetIds = this.GetStringValuesOrDefault(this.SubnetIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, false)?.ToList(), SecurityGroupIds = this.GetStringValuesOrDefault(this.SecurityGroupIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, false)?.ToList() } }; var environmentVariables = GetEnvironmentVariables(null); if (environmentVariables != null && environmentVariables.Count > 0) { createRequest.Environment = new Model.Environment { Variables = environmentVariables }; } var tags = this.GetKeyValuePairOrDefault(this.Tags, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, false); if (tags != null && tags.Count > 0) { createRequest.Tags = tags; } var deadLetterQueue = this.GetStringValueOrDefault(this.DeadLetterTargetArn, LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, false); if (!string.IsNullOrEmpty(deadLetterQueue)) { createRequest.DeadLetterConfig = new DeadLetterConfig { TargetArn = deadLetterQueue }; } var tracingMode = this.GetStringValueOrDefault(this.TracingMode, LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE, false); if (!string.IsNullOrEmpty(tracingMode)) { createRequest.TracingConfig = new TracingConfig { Mode = tracingMode }; } if (s3Bucket != null) { createRequest.Code = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key }; } else { createRequest.Code = new FunctionCode { ZipFile = stream }; } try { await this.LambdaClient.CreateFunctionAsync(createRequest); this.Logger.WriteLine("New Lambda function created"); } catch (Exception e) { throw new LambdaToolsException($"Error creating Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaCreateFunction, e); } } else { this.Logger.WriteLine($"Updating code for existing function {this.FunctionName}"); var updateCodeRequest = new UpdateFunctionCodeRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true) }; if (s3Bucket != null) { updateCodeRequest.S3Bucket = s3Bucket; updateCodeRequest.S3Key = s3Key; } else { updateCodeRequest.ZipFile = stream; } try { await this.LambdaClient.UpdateFunctionCodeAsync(updateCodeRequest); } catch (Exception e) { throw new LambdaToolsException($"Error updating code for Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaUpdateFunctionCode, e); } await base.UpdateConfigAsync(currentConfiguration); await base.ApplyTags(currentConfiguration.FunctionArn); var publish = this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(); if (publish) { await base.PublishFunctionAsync(updateCodeRequest.FunctionName); } } } return(true); }