Beispiel #1
0
        private async Task Commit(Func <Task> f, string stackName, StackStatus targetStatus)
        {
            try
            {
                await f();
            }
            catch (AmazonCloudFormationException ex)
            {
                // evil
                if (ex.ErrorCode == "ValidationError" && ex.Message == "No updates are to be performed.")
                {
                    _logger.Info("No stack updates required");
                }
                else
                {
                    _logger.Error(ex, "Failed to create or update stack");
                    throw;
                }

                return;
            }

            var didComplete = await WaitForStackToReachStatus(stackName, targetStatus);

            if (!didComplete)
            {
                throw new Exception("Cloudformation stack did reach target status");
            }
        }
Beispiel #2
0
        /// <summary>
        /// Sets up the cloud formation operations for most tests.
        /// </summary>
        /// <param name="stackStatus">The stack status.</param>
        /// <returns>A <see cref="CloudFormationOperations"/> for the test</returns>
        private CloudFormationOperations SetupCloudFormationOperations(string stackStatus)
        {
            var logger            = new TestLogger(this.output);
            var mockClientFactory = TestHelpers.GetClientFactoryMock();
            var mockContext       = TestHelpers.GetContextMock(logger);

            var mockCf = new Mock <IAmazonCloudFormation>();

            mockCf.Setup(cf => cf.DescribeStacksAsync(It.IsAny <DescribeStacksRequest>(), default)).ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName = StackName, StackStatus = StackStatus.FindValue(stackStatus)
                    }
                }
            });

            mockClientFactory.Setup(f => f.CreateCloudFormationClient()).Returns(mockCf.Object);

            var operations = new CloudFormationOperations(mockClientFactory.Object, mockContext.Object);

            return(operations);
        }
Beispiel #3
0
        /// <summary>
        /// Check to see if the stack name exists.
        /// </summary>
        /// <param name="defaultValue">The return value when the user does not have the permissions to query the stacks</param>
        /// <returns>The current status of the stack</returns>
        private StackStatus StackExists(StackStatus defaultValue)
        {
            try
            {
                return(new AmazonCloudFormationClient(awsEnvironmentGeneration.AwsCredentials,
                                                      new AmazonCloudFormationConfig
                {
                    RegionEndpoint = awsEnvironmentGeneration.AwsRegion,
                    ProxyPort = awsEnvironmentGeneration.ProxyPort,
                    ProxyCredentials = awsEnvironmentGeneration.ProxyCredentials,
                    ProxyHost = awsEnvironmentGeneration.ProxyHost
                })
                       // The client becomes the result of the API call
                       .Map(client => client.DescribeStacks(new DescribeStacksRequest {
                    StackName = stackName
                }))
                       // The result becomes true/false based on the presence of a matching stack name
                       .Map(result => result.Stacks.FirstOrDefault())
                       // Does the status indicate that processing has finished?
                       ?.Map(stack => (stack.StackStatus?.Value.EndsWith("_COMPLETE") ?? true) ||
                             (stack.StackStatus.Value.EndsWith("_FAILED")))
                       // Convert the result to a StackStatus
                       .Map(completed => completed ? StackStatus.Completed : StackStatus.InProgress)
                       // Of, if there was no stack that matched the name, the stack does not exist
                       ?? StackStatus.DoesNotExist);
            }
            catch (AmazonCloudFormationException ex)
            {
                if (ex.ErrorCode == "AccessDenied")
                {
                    DisplayWarning(
                        "AWS-CLOUDFORMATION-ERROR-0003",
                        "The AWS account used to perform the operation does not have " +
                        "the required permissions to describe the stack.\n" +
                        ex.Message);

                    return(defaultValue);
                }

                // This is OK, we just return the fact that the stack does not exist.
                // While calling describe stacks and catching exceptions seems dirty,
                // this is how the stack-exists command on the CLI works:
                // https://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/stack-exists.html
                if (ex.ErrorCode == "ValidationError")
                {
                    return(StackStatus.DoesNotExist);
                }

                throw new UnknownException(
                          "AWS-CLOUDFORMATION-ERROR-0006: An unrecognised exception was thrown while checking to see if the CloudFormation stack exists.\n" +
                          "For more information visit https://g.octopushq.com/AwsCloudFormationDeploy#aws-cloudformation-error-0006",
                          ex);
            }
            catch (AmazonServiceException ex)
            {
                HandleAmazonServiceException(ex);
                throw ex;
            }
        }
Beispiel #4
0
        public void SetStackExtender(IStack aStackExtender)
        {
            StackStatus status = Stack.Status;

            Assert.Check(iStackExtender == null);
            Assert.Check(status.State == EStackState.eStopped);
            iStackExtender = aStackExtender;
        }
Beispiel #5
0
        private void OnLoad(object sender, EventArgs e)
        {
            iHelper.Stack.Start();

            StackStatus status = iHelper.Stack.Status;

            if (status.State != EStackState.eOk)
            {
                ShowOptionsDialog();
            }
        }
Beispiel #6
0
 private void CheckStatus()
 {
     foreach (Box box in boxList)
     {
         if (box.status != BoxStatus.Success)
         {
             return;
         }
     }
     stackStatus = StackStatus.Success;
 }
        public static async Task CreateQueuesForEndpoint(string endpointName, string templatePath, TimeSpan?maxTimeToLive = null, string queueNamePrefix = null, bool includeRetries = false, string delayedDeliveryMethod = "Native")
        {
            using (var client = ClientFactory.CreateCloudFormationClient())
            {
                var endpointNameWithPrefix = QueueNameHelper.GetSqsQueueName(endpointName, queueNamePrefix);
                var request = new CreateStackRequest
                {
                    StackName  = endpointNameWithPrefix,
                    Parameters = new List <Parameter>
                    {
                        new Parameter
                        {
                            ParameterKey   = "EndpointName",
                            ParameterValue = endpointNameWithPrefix
                        },
                        new Parameter
                        {
                            ParameterKey   = "MaxTimeToLive",
                            ParameterValue = Convert.ToInt32((maxTimeToLive ?? QueueCreationUtils.DefaultTimeToLive).TotalSeconds).ToString()
                        },
                        new Parameter
                        {
                            ParameterKey   = "IncludeRetries",
                            ParameterValue = includeRetries.ToString()
                        },
                        new Parameter
                        {
                            ParameterKey   = "DelayedDeliveryMethod",
                            ParameterValue = delayedDeliveryMethod
                        },
                    },
                    TemplateBody = CloudFormationHelper.ConvertToValidJson(templatePath)
                };

                await client.CreateStackAsync(request)
                .ConfigureAwait(false);

                var describeRequest = new DescribeStacksRequest
                {
                    StackName = endpointNameWithPrefix
                };

                StackStatus currentStatus = string.Empty;
                while (currentStatus != StackStatus.CREATE_COMPLETE)
                {
                    var response = await client.DescribeStacksAsync(describeRequest)
                                   .ConfigureAwait(false);

                    var stack = response.Stacks.SingleOrDefault();
                    currentStatus = stack?.StackStatus;
                    await Task.Delay(1000);
                }
            }
        }
Beispiel #8
0
 private void CheckStatus()
 {
     if (boxList.TrueForAll(box => box.status == BoxStatus.Success) == true)
     {
         Log.log.Info("stack sort success");
         stackStatus = StackStatus.Finished;
         SortingTimerStop();
         ReportContainer(SeqNum);
         CheckStackSeq();
     }
 }
Beispiel #9
0
 public void Rescan()
 {
     lock (this)
     {
         StackStatus status = Stack.Status;
         if (status.State == EStackState.eOk)
         {
             iTopologyHouse.Rescan();
             iSenders.Rescan();
         }
     }
 }
Beispiel #10
0
 private StackStatus WaitForStackDeleted(StackStatus status, string stackName)
 {
     while (status == StackStatus.DELETE_IN_PROGRESS)
     {
         var stack = _cloudFormationClient.ListStacks().StackSummaries.First(s => s.StackName == stackName);
         status = stack.StackStatus;
         if (status == StackStatus.DELETE_IN_PROGRESS)
         {
             Thread.Sleep(TimeSpan.FromSeconds(10));
         }
     }
     return(status);
 }
Beispiel #11
0
 private CreateChangeSetRequest CreateChangesetRequest(StackStatus status, string changesetName, StackArn stack, string roleArn, CloudFormationTemplate template, List <string> capabilities)
 {
     return(new CreateChangeSetRequest
     {
         StackName = stack.Value,
         TemplateBody = template.Content,
         Parameters = template.Inputs.ToList(),
         ChangeSetName = changesetName,
         ChangeSetType = status == StackStatus.DoesNotExist ? ChangeSetType.CREATE : ChangeSetType.UPDATE,
         Capabilities = capabilities,
         RoleARN = roleArn
     });
 }
Beispiel #12
0
        public void StateChange(StackStatus state)
        {
            switch (state)
            {
            case StackStatus.Stopped:
            case StackStatus.Background:
                Proxy.ViewStatus = VisualStatus.Hidden;
                Status           = StackStatus.Background;
                // Removes No History from last page of previous stack
                NoHistoryRemoval();
                break;

            case StackStatus.Started:
                Status = StackStatus.Started;
                break;
            }
        }
        public static async Task WaitForStackStatus(string stackName, StackStatus finalStatus)
        {
            StackStatus currentStatus = await GetStackStatus(stackName);

            while (currentStatus != finalStatus)
            {
                if (!currentStatus.ToString().Contains("IN_PROGRESS"))
                {
                    throw new Exception($"Error while creation or updating stack: {currentStatus}");
                }
                Console.WriteLine(currentStatus);
                await Task.Delay(20000);

                currentStatus = await GetStackStatus(stackName);
            }
            Console.WriteLine(currentStatus);
        }
        public static async Task CreateQueue(string queueName, string templatePath, TimeSpan?maxTimeToLive = null, string queueNamePrefix = null)
        {
            using (var client = ClientFactory.CreateCloudFormationClient())
            {
                var sqsQueueName = QueueNameHelper.GetSqsQueueName(queueName, queueNamePrefix);
                var request      = new CreateStackRequest
                {
                    StackName  = sqsQueueName,
                    Parameters = new List <Parameter>
                    {
                        new Parameter
                        {
                            ParameterKey   = "QueueName",
                            ParameterValue = sqsQueueName
                        },
                        new Parameter
                        {
                            ParameterKey   = "MaxTimeToLive",
                            ParameterValue = Convert.ToInt32((maxTimeToLive ?? DefaultTimeToLive).TotalSeconds).ToString()
                        }
                    },
                    TemplateBody = CloudFormationHelper.ConvertToValidJson(templatePath)
                };

                await client.CreateStackAsync(request)
                .ConfigureAwait(false);

                var describeRequest = new DescribeStacksRequest
                {
                    StackName = sqsQueueName
                };
                StackStatus currentStatus = string.Empty;
                while (currentStatus != StackStatus.CREATE_COMPLETE)
                {
                    var response = await client.DescribeStacksAsync(describeRequest)
                                   .ConfigureAwait(false);

                    var stack = response.Stacks.SingleOrDefault();
                    currentStatus = stack?.StackStatus;
                    await Task.Delay(1000);
                }
            }
        }
Beispiel #15
0
        public void ShouldFailIfStackBusyAndWaitIsFalse(string stackStatus)
        {
            var expectedMessage    = "Stack is being modified by another process.";
            var logger             = new TestLogger(this.output);
            var mockClientFactory  = TestHelpers.GetClientFactoryMock();
            var mockContext        = TestHelpers.GetContextMock(logger);
            var mockCloudFormation = new Mock <IAmazonCloudFormation>();

            mockCloudFormation.SetupSequence(cf => cf.DescribeStacksAsync(It.IsAny <DescribeStacksRequest>(), default))
            .ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName   = StackName,
                        StackStatus = StackStatus.FindValue(stackStatus)
                    }
                }
            }).ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName   = StackName,
                        StackStatus = StackStatus.FindValue(stackStatus)
                    }
                }
            });

            mockClientFactory.Setup(f => f.CreateCloudFormationClient()).Returns(mockCloudFormation.Object);

            var runner = CloudFormationRunner.Builder(mockContext.Object, StackName)
                         .WithClientFactory(mockClientFactory.Object)
                         .WithTemplateLocation(this.fixture.TestStackJsonTemplate.FullPath).Build();

            Func <Task <CloudFormationResult> > action = async() => await runner.UpdateStackAsync(null);

            action.Should().Throw <StackOperationException>().WithMessage(expectedMessage);
        }
Beispiel #16
0
        public int AddBoxList(List <string> tBoxList)
        {
            Reset();
            boxList.Clear();
            nodeSeqList.Clear();
            foreach (string str in tBoxList)
            {
                string[] sArray = str.Split(' ');
                Box      box    = new Box();
                box.barcode = sArray[0];
                box.exNode  = Convert.ToInt16(sArray[1]);
                box.exLane  = Convert.ToInt16(sArray[2]);
                box.status  = BoxStatus.Missing;
                boxList.Add(box);

                int index;
                try
                {
                    index = nodeSeqList.FindIndex((NodeSeq mNodeSeq) =>
                    {
                        if (mNodeSeq.node == box.exNode)
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    });
                    nodeSeqList[index].AddBox(box);
                }
                catch
                {
                    NodeSeq nodeSeq = new NodeSeq(box.exNode);
                    nodeSeqList.Add(nodeSeq);
                    nodeSeq.AddBox(box);
                }
            }

            stackStatus = StackStatus.Busying;
            return(boxList.Count);
        }
        private static async Task WaitForStackStatus(string stackName, StackStatus expectedStatus, Credentials credentials)
        {
            StackStatus stackStatus = await GetStackStatus(stackName, credentials);

            while (stackStatus != expectedStatus)
            {
                Console.WriteLine($"{stackStatus}...");

                if (!stackStatus.ToString().EndsWith("_IN_PROGRESS"))
                {
                    throw new System.InvalidOperationException($"Unexpected status {stackStatus}");
                }

                await Task.Delay(TimeSpan.FromSeconds(15));

                stackStatus = await GetStackStatus(stackName, credentials);
            }

            Console.WriteLine($"Stack {stackName} successfully reached {stackStatus} status.");
        }
    public async Task <IActionResult> ChangeStatusAsync(string ids, StackStatus status)
    {
        if (status == StackStatus.Regressed || status == StackStatus.Snoozed)
        {
            return(BadRequest("Can't set stack status to regressed or snoozed."));
        }

        var stacks = await GetModelsAsync(ids.FromDelimitedString(), false);

        if (!stacks.Any())
        {
            return(NotFound());
        }

        stacks = stacks.Where(s => s.Status != status).ToList();
        if (stacks.Count > 0)
        {
            foreach (var stack in stacks)
            {
                stack.Status = status;
                if (status == StackStatus.Fixed)
                {
                    stack.DateFixed = DateTime.UtcNow;
                }
                else
                {
                    stack.DateFixed      = null;
                    stack.FixedInVersion = null;
                }

                if (status != StackStatus.Snoozed)
                {
                    stack.SnoozeUntilUtc = null;
                }
            }

            await _stackRepository.SaveAsync(stacks);
        }

        return(Ok());
    }
Beispiel #19
0
        private async Task <bool> WaitForStackToReachStatus(string stackName, StackStatus desiredStatus)
        {
            var elapsed = TimeSpan.Zero;

            do
            {
                await Task.Delay(_stackStatusCheckInterval);

                var stacksResponse = await _cloudformation.DescribeStacksAsync(new DescribeStacksRequest
                {
                    StackName = stackName
                });

                var stack = stacksResponse?.Stacks?.FirstOrDefault();

                if (stack == null)
                {
                    throw new Exception($"Stack {stackName} not returned by describeStacks");
                }

                if (stack.StackStatus == desiredStatus)
                {
                    _logger.Info($"Stack {stackName} reached target status {stack.StackStatus}");
                    return(true);
                }

                if (elapsed >= _stackStatusCheckTimeout)
                {
                    _logger.Error($"Stack {stackName} change timeout reached");
                    return(false);
                }

                if (_stackFailureStatuses.Contains(stack.StackStatus.ToString(), StringComparer.InvariantCultureIgnoreCase))
                {
                    _logger.Error($"Stack {stackName} reached status {stack.StackStatus} with reason {stack.StackStatusReason}");
                    return(false);
                }

                _logger.Info($"Stack {stackName} at status {stack.StackStatus}, waiting");
            } while (true);
        }
        public void ShouldFailIfStackIsBrokenOrBusy(string stackStatus, StackOperationalState expectedOutcome)
        {
            var logger             = new TestLogger(this.output);
            var mockClientFactory  = TestHelpers.GetClientFactoryMock();
            var mockContext        = TestHelpers.GetContextMock(logger);
            var mockCloudFormation = new Mock <IAmazonCloudFormation>();

            mockCloudFormation.SetupSequence(cf => cf.DescribeStacksAsync(It.IsAny <DescribeStacksRequest>(), default))
            .ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName = StackName, StackStatus = StackStatus.FindValue(stackStatus)
                    }
                }
            }).ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName = StackName, StackStatus = StackStatus.FindValue(stackStatus)
                    }
                }
            });

            mockClientFactory.Setup(f => f.CreateCloudFormationClient()).Returns(mockCloudFormation.Object);

            var runner = CloudFormationRunner.Builder(mockContext.Object, StackName)
                         .WithClientFactory(mockClientFactory.Object)
                         .Build();

            Func <Task <CloudFormationResult> > action = async() => await runner.DeleteStackAsync();

            action.Should().Throw <StackOperationException>().And.OperationalState.Should().Be(expectedOutcome);
        }
Beispiel #21
0
        public static async Task DeleteQueuesForEndpoint(string endpointName, string queueNamePrefix = null)
        {
            using (var client = ClientFactory.CreateCloudFormationClient())
            {
                var endpointNameWithPrefix = QueueNameHelper.GetSqsQueueName(endpointName, queueNamePrefix);

                var request = new DeleteStackRequest
                {
                    StackName = endpointNameWithPrefix,
                };


                await client.DeleteStackAsync(request)
                .ConfigureAwait(false);


                var describeRequest = new DescribeStacksRequest
                {
                    StackName = endpointNameWithPrefix
                };
                StackStatus currentStatus = string.Empty;
                while (currentStatus != StackStatus.DELETE_IN_PROGRESS) // in progress is enough, no need to wait for completion
                {
                    try
                    {
                        var response = await client.DescribeStacksAsync(describeRequest)
                                       .ConfigureAwait(false);

                        var stack = response.Stacks.SingleOrDefault();
                        currentStatus = stack?.StackStatus;
                        await Task.Delay(1000);
                    }
                    catch (AmazonCloudFormationException)
                    {
                        Console.WriteLine("Stack does not exist");
                        return;
                    }
                }
            }
        }
Beispiel #22
0
        public static async Task DeleteQueue(string queueName, string queueNamePrefix = null)
        {
            using (var client = ClientFactory.CreateCloudFormationClient())
            {
                var sqsQueueName = QueueNameHelper.GetSqsQueueName(queueName, queueNamePrefix);

                var request = new DeleteStackRequest
                {
                    StackName = sqsQueueName,
                };


                await client.DeleteStackAsync(request)
                .ConfigureAwait(false);

                var describeRequest = new DescribeStacksRequest
                {
                    StackName = sqsQueueName
                };
                StackStatus currentStatus = string.Empty;
                while (currentStatus != StackStatus.DELETE_COMPLETE)
                {
                    try
                    {
                        var response = await client.DescribeStacksAsync(describeRequest)
                                       .ConfigureAwait(false);

                        var stack = response.Stacks.SingleOrDefault();
                        currentStatus = stack?.StackStatus;
                    }
                    catch (AmazonCloudFormationException)
                    {
                        Console.WriteLine("Stack does not exist");
                        return;
                    }
                }
            }
        }
Beispiel #23
0
        public void HanderRes(DivertRes divertRes)
        {
            int index = LocationBox(divertRes.codeStr, false);

            if (index >= 0)
            {
                Box box = boxList[index];
                if (box.status == BoxStatus.Sorting)
                {
                    if ((box.exNode == divertRes.nodeId) && (box.exLane == divertRes.laneId))
                    {
                        box.status = BoxStatus.Success;
                        CheckStatus();
                    }
                    else
                    {
                        Log.log.Error("box with barcode: " + box.barcode + " sorting falut: " + divertRes.divertRes);
                        stackStatus = StackStatus.SortFalut;
                        throw new Exception();
                    }
                }
            }
        }
Beispiel #24
0
        private int AddBoxList(List <Box> tBoxList)
        {
            foreach (Box box in tBoxList)
            {
                boxList.Add(box);
                int index;
                index = nodeSeqList.FindIndex(mNodeSeq => mNodeSeq.node == box.node);
                if (index == -1)
                {
                    NodeSeq nodeSeq = new NodeSeq(box.node);
                    nodeSeqList.Add(nodeSeq);
                    nodeSeq.AddBox(box);
                }
                else
                {
                    nodeSeqList[index].AddBox(box);
                }
            }

            stackStatus = StackStatus.CheckingBox;

            return(boxList.Count);
        }
Beispiel #25
0
        public static Stack GenerateStack(bool generateId = false, string id = null, string organizationId = null, string projectId = null, string type = null, string title = null, DateTime?dateFixed = null, DateTime?utcFirstOccurrence = null, DateTime?utcLastOccurrence = null, int totalOccurrences = 0, StackStatus status = StackStatus.Open, string signatureHash = null)
        {
            var stack = new Stack {
                Id               = id.IsNullOrEmpty() ? generateId ? ObjectId.GenerateNewId().ToString() : null : id,
                OrganizationId   = organizationId.IsNullOrEmpty() ? TestConstants.OrganizationId : organizationId,
                ProjectId        = projectId.IsNullOrEmpty() ? TestConstants.ProjectIds.Random() : projectId,
                Title            = title ?? RandomData.GetTitleWords(),
                Type             = type ?? Stack.KnownTypes.Error,
                DateFixed        = dateFixed,
                FirstOccurrence  = utcFirstOccurrence ?? DateTime.MinValue,
                LastOccurrence   = utcLastOccurrence ?? DateTime.MinValue,
                TotalOccurrences = totalOccurrences,
                Status           = status,
                SignatureHash    = signatureHash ?? RandomData.GetAlphaNumericString(10, 10),
                SignatureInfo    = new SettingsDictionary()
            };

            stack.DuplicateSignature = String.Concat(stack.ProjectId, ":", stack.SignatureHash);

            if (type == Event.KnownTypes.Error)
            {
                stack.SignatureInfo.Add("ExceptionType", TestConstants.ExceptionTypes.Random());
            }

            for (int i = 0; i < RandomData.GetInt(0, 5); i++)
            {
                string tag = RandomData.GetWord();
                while (stack.Tags.Contains(tag))
                {
                    tag = RandomData.GetWord();
                }

                stack.Tags.Add(tag);
            }

            return(stack);
        }
        public async void ShouldDeleteStackIfStackExistsAndIsInCorrectState(string status)
        {
            var logger            = new TestLogger(this.output);
            var mockClientFactory = TestHelpers.GetClientFactoryMock();
            var mockContext       = TestHelpers.GetContextMock(logger);

            var mockCloudFormation = new Mock <IAmazonCloudFormation>();

            mockCloudFormation.SetupSequence(cf => cf.DescribeStacksAsync(It.IsAny <DescribeStacksRequest>(), default))
            .ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName = StackName, StackStatus = StackStatus.FindValue(status)
                    }
                }
            }).ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName = StackName, StackStatus = StackStatus.FindValue(status)
                    }
                }
            }).ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName = StackName, StackStatus = StackStatus.DELETE_IN_PROGRESS
                    }
                }
            }).ReturnsAsync(
                new DescribeStacksResponse
            {
                Stacks = new List <Stack>
                {
                    new Stack()
                    {
                        StackName = StackName, StackStatus = StackStatus.DELETE_COMPLETE
                    }
                }
            });

            mockCloudFormation.Setup(cf => cf.DeleteStackAsync(It.IsAny <DeleteStackRequest>(), default))
            .ReturnsAsync(new DeleteStackResponse());

            mockCloudFormation.SetupSequence(cf => cf.DescribeStackEventsAsync(It.IsAny <DescribeStackEventsRequest>(), default))
            .ReturnsAsync(
                new DescribeStackEventsResponse
            {
                StackEvents = new List <StackEvent>
                {
                    new StackEvent
                    {
                        StackName      = StackName,
                        StackId        = StackId,
                        ResourceStatus = status,
                        Timestamp      = DateTime.Now.AddDays(-1)
                    }
                }
            })
            .ReturnsAsync(
                new DescribeStackEventsResponse
            {
                StackEvents = new List <StackEvent>
                {
                    new StackEvent
                    {
                        StackName      = StackName,
                        StackId        = StackId,
                        ResourceStatus = ResourceStatus.DELETE_COMPLETE,
                        Timestamp      = DateTime.Now.AddSeconds(1)
                    }
                }
            })
            .ReturnsAsync(
                new DescribeStackEventsResponse
            {
                StackEvents = new List <StackEvent>()
            });

            mockCloudFormation.Setup(cf => cf.DescribeStackResourcesAsync(It.IsAny <DescribeStackResourcesRequest>(), default))
            .ReturnsAsync(new DescribeStackResourcesResponse {
                StackResources = new List <StackResource>()
            });

            mockCloudFormation.Setup(cf => cf.GetTemplateAsync(It.IsAny <GetTemplateRequest>(), default)).ReturnsAsync(
                new GetTemplateResponse
            {
                TemplateBody = this.fixture.TestStackJsonString
            });

            mockCloudFormation.Setup(cf => cf.GetTemplateSummaryAsync(It.IsAny <GetTemplateSummaryRequest>(), default))
            .ReturnsAsync(new GetTemplateSummaryResponse {
                Parameters = new List <ParameterDeclaration>()
            });

            mockClientFactory.Setup(f => f.CreateCloudFormationClient()).Returns(mockCloudFormation.Object);
            var runner = CloudFormationRunner.Builder(mockContext.Object, StackName)
                         .WithClientFactory(mockClientFactory.Object)
                         .WithFollowOperation()
                         .Build();

            (await runner.DeleteStackAsync()).StackOperationResult.Should().Be(StackOperationResult.StackDeleted);
            logger.StackEvents.Count.Should().BeGreaterThan(0);
        }
Beispiel #27
0
    public EventDataBuilder Status(StackStatus status)
    {
        _stackMutations.Add(s => s.Status = status);

        return(this);
    }
Beispiel #28
0
        public TestEventBuilder Status(StackStatus status)
        {
            _stackMutations.Add(s => s.Status = StackStatus.Open);

            return(this);
        }
 /// <summary>
 /// Check to see if the stack name exists.
 /// </summary>
 /// <param name="defaultValue">The return value when the user does not have the permissions to query the stacks</param>
 /// <returns>The current status of the stack</returns>
 private Task <StackStatus> StackExists(StackArn stack, StackStatus defaultValue)
 {
     return(WithAmazonServiceExceptionHandling(() => clientFactory.StackExistsAsync(stack, defaultValue)));
 }
 /// <summary>
 /// Check to see if the stack name exists.
 /// </summary>
 /// <param name="defaultValue">The return value when the user does not have the permissions to query the stacks</param>
 /// <returns>The current status of the stack</returns>
 async Task <StackStatus> StackExists(StackArn stack, StackStatus defaultValue)
 {
     return(await WithAmazonServiceExceptionHandling(async() => await clientFactory.StackExistsAsync(stack, defaultValue)));
 }