public void UpdateRedis(bool serverTerminated = false) { var gameServerStatusData = new GameServerStatusData(); gameServerStatusData.taskArn = this.taskDataArnWithContainer; gameServerStatusData.currentPlayers = this.server.GetPlayerCount(); gameServerStatusData.maxPlayers = Server.maxPlayers; gameServerStatusData.publicIP = this.publicIP; gameServerStatusData.port = Server.port; gameServerStatusData.serverTerminated = serverTerminated; gameServerStatusData.gameSessionsHosted = Server.hostedGameSessions; var lambdaConfig = new AmazonLambdaConfig() { RegionEndpoint = this.regionEndpoint }; lambdaConfig.MaxErrorRetry = 0; //Don't do retries on failures var lambdaClient = new Amazon.Lambda.AmazonLambdaClient(lambdaConfig); // Option 1. If TCPListener is not ready yet, update as not ready if (!this.server.IsReady()) { Debug.Log("Updating as not ready yet to Redis"); gameServerStatusData.ready = false; gameServerStatusData.serverInUse = false; } // Option 2. If not full yet but, update our status as ready else if (this.server.IsReady() && this.server.GetPlayerCount() < Server.maxPlayers) { Debug.Log("Updating as ready to Redis"); gameServerStatusData.ready = true; gameServerStatusData.serverInUse = false; } // Option 3. If full, make sure the available key is deleted in Redis and update the full key else { Debug.Log("Updating as full to Redis"); gameServerStatusData.ready = true; gameServerStatusData.serverInUse = true; } // Call Lambda function to update status var request = new Amazon.Lambda.Model.InvokeRequest() { FunctionName = "FargateGameServersUpdateGameServerData", Payload = JsonConvert.SerializeObject(gameServerStatusData), InvocationType = InvocationType.Event }; // NOTE: We could catch response to validate it was successful and do something useful with that information lambdaClient.InvokeAsync(request); }
public static void Initialize() { LambdaClient = new AmazonLambdaClient(TestRunner.Credentials, TestRunner.RegionEndpoint); IAMClient = new AmazonIdentityManagementServiceClient(TestRunner.Credentials, TestRunner.RegionEndpoint); RoleArn = UtilityMethods.CreateRoleIfNotExists(IAMClient, RoleName, UtilityMethods.LambdaAssumeRolePolicyDocument); UtilityMethods.CreatePolicyIfNotExists(IAMClient, RolePolicyName, RolePolicyDocument, RoleName); foreach (string[] functionInfo in FunctionNames) { CreateFunction(functionInfo[0], functionInfo[1], functionInfo[2]); } }
public void TestInvokeResponseBody() { var responseBody = "Process exited before completing request:TypeError: Object #<LambdaEventResponse> has no method 'write': at exports.handler (/var/task/helloworld.js:4:14)"; var requestId = "fakerequ-esti-dfak-ereq-uestidfakere"; using(var client = new Amazon.Lambda.AmazonLambdaClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast1)) { CustomResponses.SetResponse(client, responseBody, requestId, isOK: true); var response = client.Invoke(new InvokeRequest { }); Assert.AreEqual(requestId, response.ResponseMetadata.RequestId); Assert.AreEqual(responseBody, Encoding.UTF8.GetString(response.Payload.ToArray())); } }
public void TestInvokeResponseBody() { var responseBody = "Process exited before completing request:TypeError: Object #<LambdaEventResponse> has no method 'write': at exports.handler (/var/task/helloworld.js:4:14)"; var requestId = "fakerequ-esti-dfak-ereq-uestidfakere"; using (var client = new Amazon.Lambda.AmazonLambdaClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast1)) { CustomResponses.SetResponse(client, responseBody, requestId, isOK: true); var response = client.Invoke(new InvokeRequest { }); Assert.AreEqual(requestId, response.ResponseMetadata.RequestId); Assert.AreEqual(responseBody, Encoding.UTF8.GetString(response.Payload.ToArray())); } }
private void HandleWaitingForTermination() { this.waitingForTerminateCounter += Time.deltaTime; // Check the status every 5 seconds if (waitingForTerminateCounter > 5.0f) { this.waitingForTerminateCounter = 0.0f; Debug.Log("Waiting for other servers in the Task to finish..."); var lambdaConfig = new AmazonLambdaConfig() { RegionEndpoint = this.regionEndpoint }; var lambdaClient = new Amazon.Lambda.AmazonLambdaClient(lambdaConfig); // Call Lambda function to check if we should terminate var taskStatusRequestData = new TaskStatusData(); taskStatusRequestData.taskArn = this.taskDataArn; var request = new Amazon.Lambda.Model.InvokeRequest() { FunctionName = "FargateGameServersCheckIfAllContainersInTaskAreDone", Payload = JsonConvert.SerializeObject(taskStatusRequestData), InvocationType = InvocationType.RequestResponse }; // As we are not doing anything else on the server anymore, we can just wait for the invoke response var invokeResponse = lambdaClient.InvokeAsync(request); invokeResponse.Wait(); invokeResponse.Result.Payload.Position = 0; var sr = new StreamReader(invokeResponse.Result.Payload); var responseString = sr.ReadToEnd(); Debug.Log("Got response: " + responseString); // Try catching to boolean, if it was a failure, this will also result in false var allServersInTaskDone = false; bool.TryParse(responseString, out allServersInTaskDone); if (allServersInTaskDone) { Debug.Log("All servers in the Task done running full amount of sessions --> Terminate"); Application.Quit(); } } }
static void Main(string[] args) { Console.WriteLine("Calling AWS function..."); Amazon.Lambda.AmazonLambdaClient client = new Amazon.Lambda.AmazonLambdaClient(Amazon.RegionEndpoint.EUWest1); var uploadRequest = new UploadRequest { S3BucketName = "afbuckets3", S3ObjectKey = "E033-21_A_PdC_RV_Anna_Monofamiliare_L1_R00.rvt", ForgeBucketKey = "gua68z8svobvpg0r5nizfxvbafna2gbd-ebuilding", ForgeModelName = "FromLambda_Torre A ARCH_20210331_3.rvt" }; var request = new InvokeRequest { FunctionName = "ForgeUploadLocalDeploy-UploadToForgeFunction-1XX2E2GUYTUMQ", // force sync lambda invocation InvocationType = InvocationType.RequestResponse, LogType = LogType.Tail, Payload = JsonSerializer.Serialize(uploadRequest) }; Stopwatch sw = new Stopwatch(); sw.Start(); var response = client.InvokeAsync(request).Result; sw.Stop(); Console.WriteLine($"Function executed in {sw.Elapsed.TotalSeconds} sec"); if (response != null) { using (var sr = new StreamReader(response.Payload)) { var result = sr.ReadToEndAsync().Result; Console.WriteLine(result); var uploadResponse = JsonSerializer.Deserialize <UploadResponse>(result); Console.WriteLine($"object key = {uploadResponse.UploadResult.objectKey}"); } } }
/// <summary> /// Create a Lambda Function or return the ARN of the existing Lambda Function with the same name. /// </summary> /// <param name="client"></param> /// <param name="functionName">Name of lambda function.</param> /// <param name="functionHandlerName">The name of the .js file that contains the Lambda handler. /// e.g helloworld.js has functionHandlerName "helloworld". </param> /// <param name="code">The Base64-encoded zip file of the code to be used. The name of the file /// in the zip file that contains the Lambda functio handler should match functionHandlerName. /// .Net 2.0 does not support System.IO.Compression.ZipArchive so the process of creating the /// Base64-encoded zip file should be done outside of the test framework in the following way: /// private static string CreateScriptBytesBase64(string name, string script) /// { /// using (var stream = new MemoryStream()) /// { /// using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true)) /// { /// var entry = archive.CreateEntry(name + ".js"); /// using (var entryStream = entry.Open()) /// using (var writer = new StreamWriter(entryStream)) /// { /// writer.Write(script); /// } /// } /// var bytes = stream.ToArray(); /// var base64 = Convert.ToBase64String(bytes); /// return base64; /// } /// } /// </param> /// <param name="iamRoleArn"></param> /// <returns></returns> public static string CreateFunctionIfNotExists(AmazonLambdaClient client, string functionName, string functionHandlerName, string code, string iamRoleArn) { AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); string functionArn = UtilityMethods.GetFunctionArnIfExists(client, functionName); if (functionArn == null) { int retries = 3; long codeSize = -1; while (retries > 0) { client.CreateFunctionAsync(new CreateFunctionRequest { FunctionName = functionName, Code = new FunctionCode { ZipFile = GetScriptStream(code) }, Handler = functionHandlerName + ".handler", Runtime = Runtime.Nodejs, Description = "Feel free to delete this function. The tests will recreate it when needed.", Role = iamRoleArn }, (response) => { responseException = response.Exception; if (responseException == null) { functionArn = response.Response.FunctionArn; codeSize = response.Response.CodeSize; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); if (responseException == null) { break; } else { Utils.AssertTrue(responseException is InvalidParameterValueException); // Need to wait longer for eventual consistency of role retries--; Thread.Sleep(TimeSpan.FromSeconds(10)); } } Assert.IsNotNull(functionArn); Utils.AssertTrue(codeSize > 0); } return functionArn; }
public String DeregisterReportedAMIs(AMICleanupInput input, ILambdaContext context) { var ec2Client = new AmazonEC2Client(); var s3client = new AmazonS3Client(); String[] lines = new AWSCommon().GetS3ContextAsText(input.BucketName, input.Key).Split("\n".ToCharArray()); int index = 0; foreach (String line in lines) { if (input.StartIndex > index) { if (index == input.StartIndex - 1) { context.Logger.LogLine($"Skipped processing up to index #{index}"); } index++; continue; } if (context.RemainingTime.Seconds < 10) { context.Logger.LogLine($"Less than 10 seconds for lambda execution, starting function recursively.."); var lambdaClient = new Amazon.Lambda.AmazonLambdaClient(); input.StartIndex = index; lambdaClient.InvokeAsync(new Amazon.Lambda.Model.InvokeRequest() { InvocationType = Amazon.Lambda.InvocationType.Event, FunctionName = context.FunctionName, Payload = JsonConvert.SerializeObject(input) }).Wait(); return("Started recursively with index=" + index); } index = index + 1; String[] cells = line.Split(','); if (cells.Length >= 3) { String amiId = cells[2]; if (amiId.StartsWith("ami-")) { try { var describeResponse = ec2Client.DescribeImagesAsync(new DescribeImagesRequest() { ImageIds = new List <String>() { amiId } }); describeResponse.Wait(); context.Logger.LogLine($"De-registering AMI {amiId}"); ec2Client.DeregisterImageAsync(new DeregisterImageRequest() { ImageId = amiId }).Wait(); describeResponse.Result.Images[0].BlockDeviceMappings.ForEach(mapping => { if (mapping.Ebs != null && mapping.Ebs.SnapshotId != null) { context.Logger.LogLine($"Deleting snapshot {mapping.Ebs.SnapshotId} for ami {amiId}"); ec2Client.DeleteSnapshotAsync(new DeleteSnapshotRequest() { SnapshotId = mapping.Ebs.SnapshotId }).Wait(); } }); } catch (Exception ex) { context.Logger.LogLine($"Failed to delete ami {amiId} with following error:"); context.Logger.LogLine(ex.ToString()); } } else { context.Logger.LogLine($"Skppingg non-ami id : {amiId}"); } } } return("OK"); }
public LambdaTestRunner(Amazon.Lambda.AmazonLambdaClient client) { _client = client; }