Пример #1
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
        {
            var client = new AmazonStepFunctionsClient();
            var sfnArn = Environment.GetEnvironmentVariable("STEP_FUNCTION_ARN");

            LambdaLogger.Log($"Processing {dynamoEvent.Records.Count()}");
            LambdaLogger.Log($"ARN {sfnArn}");
            IList <DynamoDBEvent.DynamodbStreamRecord> r = dynamoEvent.Records;

            foreach (DynamoDBEvent.DynamodbStreamRecord record in dynamoEvent.Records)
            {
                if (record.EventName == OperationType.INSERT)
                {
                    var incoming = record.Dynamodb.NewImage.ToDynamoEntity <PurchaseOrder>();
                    LambdaLogger.Log($"ID {incoming.PurchaseId}");
                    LambdaLogger.Log($"Color {incoming.ColorName}");
                    var request = new StartExecutionRequest()
                    {
                        Input = JsonSerializer.Serialize(new {
                            PurchasedInventory = new object[] { incoming }
                        }),
                        Name            = Guid.NewGuid().ToString(),
                        StateMachineArn = sfnArn,
                    };

                    var resp = await client.StartExecutionAsync(request);

                    if (resp.HttpStatusCode != System.Net.HttpStatusCode.OK)
                    {
                        throw new Exception($"Failed with code {resp.HttpStatusCode}: {JsonSerializer.Serialize(resp.ResponseMetadata)}");
                    }
                }
            }
        }
Пример #2
0
        static void ExecuteStepFunctionUsingAssumedExistingStateMachineRole()
        {
            var options = new AWSOptions()
            {
                Profile = "default",
                Region  = RegionEndpoint.EUWest2
            };

            var assumedRoleResponse       = ManualAssume(options).ConfigureAwait(false).GetAwaiter().GetResult();
            var assumedCredentials        = assumedRoleResponse.Credentials;
            var amazonStepFunctionsConfig = new AmazonStepFunctionsConfig {
                RegionEndpoint = RegionEndpoint.EUWest2
            };

            using (var amazonStepFunctionsClient = new AmazonStepFunctionsClient(
                       assumedCredentials.AccessKeyId,
                       assumedCredentials.SecretAccessKey, amazonStepFunctionsConfig))
            {
                var state = new State
                {
                    Name = "MyStepFunctions"
                };
                var jsonData1             = JsonConvert.SerializeObject(state);
                var startExecutionRequest = new StartExecutionRequest
                {
                    Input           = jsonData1,
                    Name            = $"SchedulingEngine_{Guid.NewGuid().ToString("N")}",
                    StateMachineArn = "arn:aws:states:eu-west-2:464534050515:stateMachine:StateMachine-z8hrOwmL9CiG"
                };
                var taskStartExecutionResponse = amazonStepFunctionsClient.StartExecutionAsync(startExecutionRequest).ConfigureAwait(false).GetAwaiter().GetResult();
            }

            Console.ReadLine();
        }
Пример #3
0
        private async Task <StartExecutionResponse> StartWorkflowInstanceAsync()
        {
            StartExecutionResponse status = null;

            try
            {
                LambdaLogger.Log("1. Lambda start1");
                List <Quote> quotes = GetQuotesAsPerStage(2, 13);//2 RSM, 13 Submitted,
                LambdaLogger.Log("1. Lambda start2");

                foreach (var item in quotes)
                {
                    //Check if any Promotion is submitted

                    //LambdaLogger.Log("1. Lambda start3"+ Directory.GetCurrentDirectory() + @"\iam.json");
                    //_CredentialProfileStoreChain = new CredentialProfileStoreChain( );//@"/iam.json"
                    //LambdaLogger.Log("Profile Location="+_CredentialProfileStoreChain.ProfilesLocation);
                    //AWSCredentials awsCredentials;
                    //if (_CredentialProfileStoreChain.TryGetAWSCredentials("default", out awsCredentials))//local-test-profile
                    //{
                    //    if (awsCredentials != null)
                    //    {
                    string inputToStepFunc = "{ \"quoteid\": \"" + item.QuoteID + "\", \"promodesc\" : \"" + item.TPBackground + "\" }";

                    var aws_access_key_id     = Environment.GetEnvironmentVariable("aws_access_key_id");
                    var aws_secret_access_key = Environment.GetEnvironmentVariable("aws_secret_access_key");
                    using (AmazonStepFunctionsClient stepfunctions = new AmazonStepFunctionsClient(aws_access_key_id, aws_secret_access_key, Amazon.RegionEndpoint.USEast1))
                    {
                        LambdaLogger.Log("Gocha credentials going to invoke Step function");
                        string nameunique = item.QuoteID + "_WF";//+"_" + DateTime.Now.ToString("ddMMyyyyHHmmssfff");
                        StartExecutionRequest newRequest = new StartExecutionRequest {
                            StateMachineArn = "arn:aws:states:us-east-1:494875521123:stateMachine:ApprovalWorkflow", Input = inputToStepFunc, Name = nameunique
                        };
                        LambdaLogger.Log("Step Func object is ready to be invoked.");
                        status = await stepfunctions.StartExecutionAsync(newRequest);

                        LambdaLogger.Log("Step Func invoke done" + status.ToString());
                    }
                    //}
                    //else
                    //    LambdaLogger.Log("Null AWS Credentilas found.");
                    //}
                    LambdaLogger.Log("Workflow is created for Quote id = " + item.QuoteID);
                }
            }
            catch (Exception ex)
            {
                LambdaLogger.Log("Error" + ex.ToString());
                throw ex;
            }
            return(status);
        }
        public async Task <NumberPlateTrigger> FunctionHandler(S3Event evnt, ILambdaContext context)
        {
            var s3Event = evnt.Records?[0].S3;

            context.Logger.LogLine("EVENT Received: " + JsonConvert.SerializeObject(s3Event));

            if (regExNumberPlate == null)
            {
                context.Logger.LogLine("regExNumberPlate is not yet populated. Calling getNumberPlateFromSecretsManager()...");
                regExNumberPlate = await getNumberPlateFromSecretsManager(context);

                context.Logger.LogLine("regExNumberPlate is " + regExNumberPlate);
            }

            NumberPlateTrigger result = new NumberPlateTrigger
            {
                bucket        = s3Event.Bucket.Name,
                key           = s3Event.Object.Key,
                contentType   = "",
                contentLength = s3Event.Object.Size,
                charge        = int.Parse(Environment.GetEnvironmentVariable("TollgateCharge")),
                numberPlate   = new NumberPlate()
                {
                    numberPlateRegEx = this.regExNumberPlate,
                    detected         = false
                }
            };

            AWSXRayRecorder recorder = AWSXRayRecorder.Instance;

            recorder.BeginSubsegment("TollGantry::Detect Number Plate in Captured Image");
            recorder.AddMetadata("bucket", s3Event.Bucket.Name);
            recorder.AddMetadata("key", s3Event.Object.Key);
            recorder.AddMetadata("regex", this.regExNumberPlate);
            //
            // TODO: Call Rekognition to detect text in the captured image
            //
            recorder.EndSubsegment();

            //
            // Kick off the step function
            //
            context.Logger.LogLine("Starting the state machine");
            IAmazonStepFunctions stepFunctionsClient = new AmazonStepFunctionsClient();
            await stepFunctionsClient.StartExecutionAsync(new StartExecutionRequest()
            {
                StateMachineArn = Environment.GetEnvironmentVariable("NumberPlateProcessStateMachine"), Input = JsonConvert.SerializeObject(result)
            });

            context.Logger.LogLine("State machine started");
            return(result);
        }
Пример #5
0
        private static async Task StartAndMonitorExecution()
        {
            string executionName = Guid.NewGuid().ToString();

            using (var client = new AmazonStepFunctionsClient(RegionEndpoint.SAEast1))
            {
                // manda executar o Step Function
                var payload = new SimpleStepFunctionInput
                {
                    Name   = "pirilampo",
                    Number = _rnd.Next()
                };

                var request = new StartExecutionRequest
                {
                    Input           = JsonConvert.SerializeObject(payload, Formatting.None, _jsonSerializerSettings),
                    Name            = executionName,
                    StateMachineArn = _stateMachineArn
                };

                Console.WriteLine("Sending:");
                Console.WriteLine(request.Input);

                var response = await client.StartExecutionAsync(request).ConfigureAwait(false);

                if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine($"Err: {response.HttpStatusCode}");
                    return;
                }

                // verifica o estado da execução
                var requestStatus = new DescribeExecutionRequest
                {
                    ExecutionArn = $"{_executionArn}:{executionName}",
                };
                while (true)
                {
                    var responseStatus = await client.DescribeExecutionAsync(requestStatus).ConfigureAwait(false);

                    if (responseStatus.HttpStatusCode == System.Net.HttpStatusCode.OK && responseStatus.Status == ExecutionStatus.SUCCEEDED)
                    {
                        dynamic parsed = JsonConvert.DeserializeObject(responseStatus.Output);
                        Console.WriteLine(JsonConvert.SerializeObject(parsed, Formatting.Indented, _jsonSerializerSettings));
                        break;
                    }

                    Console.WriteLine($"{responseStatus.Status}...");
                    await Task.Delay(1500).ConfigureAwait(false);
                }
            }
        }
Пример #6
0
        public async Task FunctionHandler(S3Event evnt, ILambdaContext context)
        {
            var s3Event = evnt.Records?[0].S3;

            if (s3Event == null)
            {
                return;
            }

            FileInfo fileInfo = new FileInfo {
                Bucket = s3Event.Bucket.Name, Key = s3Event.Object.Key
            };

            string input = JsonConvert.SerializeObject(fileInfo);

            StartExecutionResponse response = await functionsClient.StartExecutionAsync(new StartExecutionRequest { Input = input, Name = Guid.NewGuid().ToString("N"), StateMachineArn = "arn:aws:states:us-east-1:518495728486:stateMachine:hackathon-2018-chegg" }).ConfigureAwait(false);
        }
Пример #7
0
 public async Task ExecuteAsync(WorkerJobHelper <WorkflowJob> job)
 {
     using (var stepFunctionClient = new AmazonStepFunctionsClient())
         await stepFunctionClient.StartExecutionAsync(
             new StartExecutionRequest
         {
             Input =
                 new
             {
                 Input = job.JobInput,
                 NotificationEndpoint = new NotificationEndpoint {
                     HttpEndpoint = job.JobAssignmentId + "/notifications"
                 }
             }.ToMcmaJson().ToString(),
             StateMachineArn = job.Request.GetRequiredContextVariable($"{job.Profile.Name}Id")
         });
 }
        public async Task <string> StartFunction(string stateMachineArn, string input, string name = null)
        {
            var response = await amazonStepFunctionsClient.StartExecutionAsync(new StartExecutionRequest()
            {
                StateMachineArn = stateMachineArn,
                Input           = input,
                Name            = name
            });

            switch (response.HttpStatusCode)
            {
            case HttpStatusCode.Accepted:
            case HttpStatusCode.OK:
                return(response.ExecutionArn);

            default:
                return(null);
            }
        }
        internal static async Task ProcessJobAssignmentAsync(WorkflowServiceWorkerRequest @event)
        {
            var resourceManager = @event.Request.GetAwsV4ResourceManager();

            var table           = new DynamoDbTable(@event.Request.StageVariables["TableName"]);
            var jobAssignmentId = @event.JobAssignmentId;

            try
            {
                // 1. Setting job assignment status to RUNNING
                await UpdateJobAssignmentStatusAsync(resourceManager, table, jobAssignmentId, "RUNNING", null);

                // 2. Retrieving WorkflowJob
                var workflowJob = await RetrieveWorkflowJobAsync(resourceManager, table, jobAssignmentId);

                // 3. Retrieve JobProfile
                var jobProfile = await RetrieveJobProfileAsync(resourceManager, workflowJob);

                // 4. Retrieve job inputParameters
                var jobInput = workflowJob.JobInput;

                // 5. Check if we support jobProfile and if we have required parameters in jobInput
                ValidateJobProfile(jobProfile, jobInput);

                // 6. Launch the appropriate workflow
                var workflowInput = new
                {
                    Input = jobInput,
                    NotificationEndpoint = new NotificationEndpoint {
                        HttpEndpoint = jobAssignmentId + "/notifications"
                    }
                };

                var startExecutionRequest = new StartExecutionRequest
                {
                    Input = workflowInput.ToMcmaJson().ToString()
                };

                switch (jobProfile.Name)
                {
                case JOB_PROFILE_CONFORM_WORKFLOW:
                    startExecutionRequest.StateMachineArn = @event.Request.StageVariables["ConformWorkflowId"];
                    break;

                case JOB_PROFILE_AI_WORKFLOW:
                    startExecutionRequest.StateMachineArn = @event.Request.StageVariables["AiWorkflowId"];
                    break;
                }

                var stepFunctionClient     = new AmazonStepFunctionsClient();
                var startExecutionResponse = await stepFunctionClient.StartExecutionAsync(startExecutionRequest);

                // 7. saving the executionArn on the jobAssignment
                var jobAssignment = await GetJobAssignmentAsync(table, jobAssignmentId);

                //TODO: Additional properties on JobAssignment? How to handle this?
                //jobAssignment.WorkflowExecutionId = startExecutionResponse.ExecutionArn;
                await PutJobAssignmentAsync(resourceManager, table, jobAssignmentId, jobAssignment);
            }
            catch (Exception error)
            {
                Logger.Exception(error);
                try
                {
                    await UpdateJobAssignmentStatusAsync(resourceManager, table, jobAssignmentId, "FAILED", error.ToString());
                }
                catch (Exception innerError)
                {
                    Logger.Exception(innerError);
                }
            }
        }
Пример #10
0
        public async Task Can_be_invoked_from_step_functions_local()
        {
            // 1. Create the StepFunctions Client
            var credentials = new BasicAWSCredentials("not", "used");
            var config      = new AmazonStepFunctionsConfig
            {
                ServiceURL = _stepFunctionsServiceUrl.ToString()
            };
            var client = new AmazonStepFunctionsClient(credentials, config);

            // 2. Create step machine with a single task the invokes a lambda function
            // The FunctionName contains the lambda to be invoked.
            var request = new CreateStateMachineRequest
            {
                Name       = "Foo",
                Type       = StateMachineType.STANDARD,
                Definition = @"{
  ""Comment"": ""A Hello World example demonstrating various state types of the Amazon States Language"",
  ""StartAt"": ""Invoke Lambda function"",
  ""States"": {
    ""Invoke Lambda function"": {
      ""Type"": ""Task"",
      ""Resource"": ""arn:aws:states:::lambda:invoke"",
      ""Parameters"": {
        ""FunctionName"": ""arn:aws:lambda:us-east-1:123456789012:function:SimpleLambdaFunction:$LATEST"",
        ""Payload"": {
          ""Input.$"": ""$.Payload""
        }
      },
      ""End"": true
    }
  }
}"
            };
            var createStateMachineResponse = await client.CreateStateMachineAsync(request);

            // 3. Create a StepFunction execution.
            var startExecutionRequest = new StartExecutionRequest
            {
                Name            = Guid.NewGuid().ToString(),
                StateMachineArn = createStateMachineResponse.StateMachineArn,
                Input           = @"{
""Payload"": { 
  ""Foo"": ""Bar"" 
  }
}"
            };
            var startExecutionResponse = await client.StartExecutionAsync(startExecutionRequest);

            var getExecutionHistoryRequest = new GetExecutionHistoryRequest
            {
                ExecutionArn         = startExecutionResponse.ExecutionArn,
                IncludeExecutionData = true,
            };

            // 4. Poll and wait for the
            while (true)
            {
                var getExecutionHistoryResponse = await client.GetExecutionHistoryAsync(getExecutionHistoryRequest);

                var historyEvent = getExecutionHistoryResponse.Events.Last();

                if (historyEvent.ExecutionSucceededEventDetails != null)
                {
                    _outputHelper.WriteLine("Execution succeeded");
                    _outputHelper.WriteLine(historyEvent.ExecutionSucceededEventDetails.Output);
                    break;
                }

                if (historyEvent.ExecutionFailedEventDetails != null)
                {
                    _outputHelper.WriteLine("Execution failed");
                    _outputHelper.WriteLine(historyEvent.ExecutionFailedEventDetails.Cause);
                    break;
                }
            }
        }
Пример #11
0
    public Status ProcessRequest(ResolverRequest request)
    {
        Status status = new Status();

        status.Id       = request.Id;
        status.ActionId = request.ActionId;

        try
        {
            String          cueId  = request.CueId;
            Config          config = JsonTools.Convert <Config>(request.Signal.Cues[cueId].Resolver.Config);
            StepFunctionArn arn    = new StepFunctionArn(config.Arn);
            RegionEndpoint  region = RegionEndpoint.GetBySystemName(System.Environment.GetEnvironmentVariable("AWS_REGION"));
            if (!String.IsNullOrEmpty(arn.Region))
            {
                region = RegionEndpoint.GetBySystemName(arn.Region);
            }

            AmazonStepFunctionsClient client = new AmazonStepFunctionsClient(region);   // Set Region

            StartExecutionRequest exeRequest = new StartExecutionRequest
            {
                StateMachineArn = config.Arn,
                Input           = JsonTools.Serialize(request)
            };

            if (config.UseDefaultName == false)
            {
                if (String.IsNullOrWhiteSpace(config.ExecutionName))
                {
                    exeRequest.Name = $"syntinel-{request.Id}-{request.ActionId}";
                }
                else
                {
                    exeRequest.Name = config.ExecutionName;
                }
            }

            Task <StartExecutionResponse> t = client.StartExecutionAsync(exeRequest);
            t.Wait(30000);
            StartExecutionResponse response = t.Result;

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                StepFunctionArn eArn = new StepFunctionArn(response.ExecutionArn);
                status.NewStatus = StatusType.SentToResolver;
                status.Message   = $"Request Sent To Step Function [{eArn.Name}].  Execution Name [{eArn.ExecutionName}].";
            }
            else
            {
                status.NewStatus = StatusType.Error;
                status.Message   = $"Error Sending To Step Function [{arn.Name}].  {response.HttpStatusCode}";
            }
        }
        catch (Exception e)
        {
            status.NewStatus = StatusType.Error;
            status.Message   = e.Message;
        }

        return(status);
    }