public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonLambdaConfig config = new AmazonLambdaConfig();

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

            ListFunctionsResponse resp = new ListFunctionsResponse();

            do
            {
                ListFunctionsRequest req = new ListFunctionsRequest
                {
                    Marker = resp.NextMarker
                    ,
                    MaxItems = maxItems
                };

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

                foreach (var obj in resp.Functions)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextMarker));
        }
Exemplo n.º 2
0
        async static Task InvokeViaSdk(Stream fileStream)
        {
            var lambdaConfig = new AmazonLambdaConfig
            {
                ServiceURL = "http://localhost:4566"
            };

            using var lambda       = new AmazonLambdaClient(lambdaConfig);
            using var memoryStream = new MemoryStream();
            fileStream.CopyTo(memoryStream);

            var getFunctionRequest = new GetFunctionRequest
            {
                FunctionName = "ConverterTronStack-ConverterTronLambda-V6ZBU97Z5XM0"
            };

            var invokeRequest = new InvokeRequest
            {
                FunctionName   = "ConverterTronStack-ConverterTronLambda-V6ZBU97Z5XM0",
                InvocationType = InvocationType.RequestResponse,
                PayloadStream  = memoryStream
            };

            var getThings = await lambda.GetFunctionAsync(getFunctionRequest);

            var response = await lambda.InvokeAsync(invokeRequest);
        }
Exemplo n.º 3
0
        private static async Task <bool> DeleteLambda(FunctionConfiguration lambda, AWSEnvironment environment)
        {
            try
            {
                var awsConfiguration = new AmazonLambdaConfig()
                {
                    RegionEndpoint = RegionEndpoint.GetBySystemName(environment.Region)
                };

                var awsCredentials = new BasicAWSCredentials(environment.AccessKey, environment.SecretKey);

                using (var awsClient = new AmazonLambdaClient(awsCredentials, awsConfiguration))
                {
                    var response = await awsClient.DeleteFunctionAsync(new DeleteFunctionRequest
                    {
                        FunctionName = lambda.FunctionName,
                        Qualifier    = lambda.Version //ARN
                    });

                    Console.WriteLine($"Lamba {lambda.FunctionName} deleted.");
                    return(response.HttpStatusCode == HttpStatusCode.NoContent); //204
                };
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine($"Error: {ex.Message}");
                Console.ForegroundColor = ConsoleColor.White;
            }
            return(false);
        }
Exemplo n.º 4
0
        private static async Task <List <FunctionConfiguration> > GetLambdaVersions(FunctionVersion functionVersion, AWSEnvironment environment)
        {
            var versionNumber = functionVersion != null ? Constants.LambdaAll : Constants.LambdaLastVersion;

            Console.WriteLine($"Reading lambda function versions: {versionNumber}");

            var result = new List <FunctionConfiguration>();

            var awsConfiguration = new AmazonLambdaConfig()
            {
                RegionEndpoint = RegionEndpoint.GetBySystemName(environment.Region)
            };

            var awsCredentials = new BasicAWSCredentials(environment.AccessKey, environment.SecretKey);

            string marker = null;

            using (var awsClient = new AmazonLambdaClient(awsCredentials, awsConfiguration))
            {
                do
                {
                    var response = await awsClient.ListFunctionsAsync(new ListFunctionsRequest
                    {
                        Marker          = marker,
                        FunctionVersion = functionVersion
                    });

                    //marker =Task<List<ListFunctionsRequest>> response.Result.NextMarker;
                    marker = response.NextMarker;
                    result.AddRange(response.Functions.Where(x => x.FunctionName.StartsWith($"{environment.Name.ToString()}")));
                } while (!string.IsNullOrEmpty(marker));

                return(result);
            }
        }
Exemplo n.º 5
0
        public override IAmazonLambda CreateLambdaClient()
        {
            var config = new AmazonLambdaConfig()
            {
                RegionEndpoint = AWSRegion
            };

            return(new AmazonLambdaClient(Credentials, config));
        }
Exemplo n.º 6
0
    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);
    }
        protected IAmazonLambda CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonLambdaConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonLambdaClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Exemplo n.º 8
0
        private IAmazonLambda CreateLambdaClient()
        {
            // If the client is being created then the LambdaTools
            // is not being invoked from the VS toolkit. The toolkit will pass in
            // its configured client.
            SetUserAgentString();


            AmazonLambdaConfig config = new AmazonLambdaConfig();

            config.RegionEndpoint = DetermineAWSRegion();

            IAmazonLambda client = new AmazonLambdaClient(DetermineAWSCredentials(), config);

            return(client);
        }
Exemplo n.º 9
0
        public ImageFunctionTests()
        {
            _executionRoleName = $"{TestIdentifier}-{Guid.NewGuid()}";
            _functionName      = $"{TestIdentifier}-{Guid.NewGuid()}";
            var lambdaConfig = new AmazonLambdaConfig()
            {
                RegionEndpoint = TestRegion
            };

            _lambdaClient = new AmazonLambdaClient(lambdaConfig);
            _iamClient    = new AmazonIdentityManagementServiceClient(TestRegion);
            _imageUri     = Environment.GetEnvironmentVariable("AWS_LAMBDA_IMAGE_URI");

            Assert.NotNull(_imageUri);

            SetupAsync().GetAwaiter().GetResult();
        }
Exemplo n.º 10
0
        public async Task <TOutput> Invoke <TInput, TOutput>(string functionName, TInput inputParam, InvocationType invocationType = null)
        {
            var lambdaConfig = new AmazonLambdaConfig()
            {
                RegionEndpoint = RegionEndpoint.GetBySystemName(AwsRegion)
            };
            var awsClient = new AmazonLambdaClient(AwsSecretAccessKeyId, AwsSecretAccessKey, lambdaConfig);

            var response = await awsClient.InvokeAsync(new InvokeRequest
            {
                FunctionName   = functionName,
                InvocationType = invocationType == null ? InvocationType.RequestResponse : invocationType,
                Payload        = JsonSerializer.Serialize(inputParam)
            });

            return(Deserialize <TOutput>(Encoding.Default.GetString(response.Payload.ToArray())));
        }
Exemplo n.º 11
0
    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();
            }
        }
    }
Exemplo n.º 12
0
        private IAmazonLambda CreateLambdaClient()
        {
            // If the Lambda client is being created then the LambdaTools
            // is not being invoked from the VS toolkit. The toolkit will pass in
            // its configured Lambda client.
            SetUserAgentString();


            AmazonLambdaConfig config = new AmazonLambdaConfig();

            var regionName = this.GetStringValueOrDefault(this.Region, DefinedCommandOptions.ARGUMENT_AWS_REGION, true);

            config.RegionEndpoint = RegionEndpoint.GetBySystemName(regionName);

            IAmazonLambda client = new AmazonLambdaClient(DetermineAWSCredentials(), config);

            return(client);
        }
Exemplo n.º 13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get the number the SMS came from,
            string fromNumber = Request["From"];

            // Create the client to be used to invoke the lambda function.
            // This will use the default credentials from the profile store.
            var config = new AmazonLambdaConfig {
                RegionEndpoint = RegionEndpoint.EUWest1
            };
            IAmazonLambda client = AWSClientFactory.CreateAmazonLambdaClient(config);

            // Arguments for the lambda function - the number the SMS came from.
            string arguments = @"{""to"": """ + fromNumber + @"""}";

            // Invoke the lambda function which will send a reply to the SMS message.
            client.InvokeAsync("SimpleSMS", arguments);
        }
Exemplo n.º 14
0
        public async Task InitializeAsync()
        {
            _settings = new LambdaTestHostSettings(() => new TestLambdaContext
            {
                Logger = new XunitLambdaLogger(_outputHelper),
            });

            _settings.AddFunction(
                new LambdaFunctionInfo(
                    nameof(BrokenFunction),
                    typeof(BrokenFunction),
                    nameof(BrokenFunction.Handle)));

            _settings.AddFunction(
                new LambdaFunctionInfo(
                    nameof(APIGatewayFunction),
                    typeof(APIGatewayFunction),
                    nameof(APIGatewayFunction.Handle)));

            _settings.AddFunction(
                new LambdaFunctionInfo(
                    nameof(ReverseStringFunction),
                    typeof(ReverseStringFunction),
                    nameof(ReverseStringFunction.Reverse)));

            _settings.AddFunction(
                new LambdaFunctionInfo(
                    nameof(SleepFunction),
                    typeof(SleepFunction),
                    nameof(SleepFunction.Handle),
                    1));

            _testHost = await LambdaTestHost.Start(_settings);

            var awsCredentials = new BasicAWSCredentials("not", "used");
            var lambdaConfig   = new AmazonLambdaConfig
            {
                ServiceURL    = _testHost.ServiceUrl.ToString().Replace("[::]", "localhost"),
                MaxErrorRetry = 0
            };

            _lambdaClient = new AmazonLambdaClient(awsCredentials, lambdaConfig);
        }
Exemplo n.º 15
0
        private MemoryStream GetAnnotationResult(InvokeRequest invokeRequest)
        {
            CheckRemainingTime();

            var config = new AmazonLambdaConfig
            {
                Timeout = TimeSpan.FromMilliseconds(_annotationTimeOut)
            };

            InvokeResponse response;

            using (var lambdaClient = new AmazonLambdaClient(config))
            {
                response = lambdaClient.InvokeAsync(invokeRequest).Result;
            }

            CheckResponse(response);
            return(response.Payload);
        }
Exemplo n.º 16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create the client to be used to invoke the lambda function.
            // This will use the default credentials from the profile store.
            var config = new AmazonLambdaConfig {
                RegionEndpoint = RegionEndpoint.EUWest1
            };
            IAmazonLambda client = AWSClientFactory.CreateAmazonLambdaClient(config);

            // Arguments for the lambda function
            const string arguments = @"{""key1"": ""argument 1"", 
                                        ""key2"": ""argument 2"",
                                        ""key3"": ""argument 3""
                                       }";

            // Invoke the lambda function
            InvokeAsyncResponse response = client.InvokeAsync("HelloWorld", arguments);

            Response.Write("Completed with response code: " + response.HttpStatusCode);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Calls a lambda function async mode (Type.Event)
        /// </summary>
        /// <param name="pFunctionName">The name of the Lambda function to call</param>
        /// <param name="pPayload">The payload to send to the Lambda</param>
        /// <returns></returns>
        public static async Task <InvokeResponse> InvokeLambdaAsync(string pFunctionName, string pPayload)
        {
            InvokeResponse     vResponse = null;
            AmazonLambdaConfig vConfig   = new AmazonLambdaConfig
            {
                RegionEndpoint = RegionEndpoint.USEast2
            };

            using (AmazonLambdaClient vClient = new AmazonLambdaClient(vConfig))
            {
                InvokeRequest vRequest = new InvokeRequest
                {
                    FunctionName   = pFunctionName,
                    InvocationType = InvocationType.Event
                };
                vRequest.Payload = pPayload;
                vResponse        = await vClient.InvokeAsync(vRequest);
            }
            return(vResponse);
        }