Skip to content

feat: stack validation improvements #4078

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 37 commits into from
Mar 28, 2025
Merged

feat: stack validation improvements #4078

merged 37 commits into from
Mar 28, 2025

Conversation

denis256
Copy link
Member

@denis256 denis256 commented Mar 24, 2025

Description

  • Added test check for not existing path for stack and unit
  • Removed unused constant for values file
  • Added validation checks on generated units and stacks to contain terragrunt files
  • Added hidden cli flag to disable validation check
  • Improved error message in case of failed unit fetching
  • Moved worker pool struct as internal
  • Documentation update

out

error

validation

Demo:

stack-validation-v2

RFC: #3313

TODOs

Read the Gruntwork contribution guidelines.

  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Ensure any 3rd party code adheres with our license policy or delete this line if its not applicable.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Added / Removed / Updated [X].

Migration Guide

Summary by CodeRabbit

  • New Features

    • Enhanced validation during stack generation now verifies that each unit and stack contains the appropriate configuration files.
    • Advanced users can bypass this validation using a new hidden command-line flag (--no-stack-validate).
    • New units and stacks have been added to support various configurations.
  • Documentation

    • Updated guides and CLI option references to include details about the new validation step and the additional flag.
  • Refactor

    • Improved error messages provide clearer feedback when stack generation encounters issues.
    • Consolidated flag management for better structure in the command-line interface.

Copy link

vercel bot commented Mar 24, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
terragrunt-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 28, 2025 2:56pm

Copy link
Contributor

coderabbitai bot commented Mar 24, 2025

📝 Walkthrough

Walkthrough

This PR introduces new Terragrunt configuration files defining units and stacks along with corresponding Terraform files. It adds integration tests for error handling during stack generation and updates the stack generation logic in the configuration package by introducing component categorization and target directory validation. A new command-line flag (NoStackValidate) and related documentation changes are included. Additionally, a new worker pool package is added for concurrent task execution, and minor formatting adjustments are applied in some CLI backend commands.

Changes

File(s) Change Summary
test/fixtures/stacks/errors/not-existing-path/live/terragrunt.stack.hcl New configuration with unit declarations for app1 and stack1.
test/fixtures/stacks/errors/incorrect-source/* New configuration and Terraform files for unit api with an incorrect source path (includes terragrunt.stack.hcl, units/api/main.tf, and units/api/terragrunt.hcl).
test/fixtures/stacks/errors/validation-stack/* Introduced new stack (stack-v1) and unit (unit-v1) configurations with corresponding Terraform and Terragrunt files for the api unit.
test/fixtures/stacks/errors/validation-unit/* Added new unit configuration for stack validation with multiple units (api, db, web) along with corresponding Terraform and Terragrunt files.
test/integration_stacks_test.go Added several constants and test functions (e.g., TestStacksNotExistingPathError, TestStacksGenerateIncorrectSource, TestStackUnitValidation, and TestStackValidation) to enhance error handling tests for stack generation.
config/stack.go Introduced a new type componentKind with constants (unitKind and stackKind), updated generation functions, and added the validateTargetDir function to include validation logic.
cli/commands/stack/cli.go Added a new hidden boolean flag NoStackValidate to disable post-generation stack validation; updated flag configuration accordingly.
options/options.go Added a new boolean field NoStackValidate to the TerragruntOptions struct with default initialization.
docs-starlight/src/data/commands/stack/generate.mdx
docs/_docs/04_reference/02-cli-options.md
Updated documentation to include the new validation feature and the --no-stack-validate flag for the terragrunt stack generate command.
internal/worker/worker.go
internal/worker/worker_test.go
Added a new worker package implementing a concurrent worker pool with functions for task submission, execution, error collection, and graceful shutdown; updated tests to use the new package.
cli/commands/backend/bootstrap/bootstrap.go
cli/commands/backend/delete/delete.go
Minor formatting changes (insertion of blank lines in error handling sections) without affecting functionality.

Sequence Diagram(s)

sequenceDiagram
    participant U as CLI User
    participant CLI as Stack CLI Command
    participant G as GenerateStacks Function
    participant V as Validator
    participant W as Worker Pool

    U->>CLI: Execute "terragrunt stack generate"
    CLI->>CLI: Parse flags (including NoStackValidate)
    CLI->>G: Invoke stack generation
    G->>V: Validate target directories (if validation enabled)
    V-->>G: Return validation results
    G->>W: Submit tasks for generating stacks/units concurrently
    W-->>G: Return task results/errors
    G-->>CLI: Return final generation result
    CLI-->>U: Display output/errors
Loading
sequenceDiagram
    participant C as Component Processor
    participant WP as Worker Pool
    participant T as Task Executor

    C->>WP: Submit task for processing component
    WP->>T: Start task in a new goroutine
    T-->>WP: Return task result or error
    WP->>WP: Collect and aggregate errors
    WP-->>C: Signal completion via Wait
Loading

Possibly related PRs

  • Stack unit path validation #3897 – Introduces unit configuration validation, directly aligning with the new unit declarations and validation logic in this PR.
  • Stack: stack values #3877 – Modifies unit value handling in stack configurations, complementing the management of new unit definitions.
  • Stacks: tests improvements #4033 – Enhances error handling and testing for stack configurations, which relates closely to the expanded error handling tests added here.

Suggested reviewers

  • levkohimins
  • yhakbar

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1d1ea9b and 850d77d.

📒 Files selected for processing (1)
  • config/config_as_cty_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • config/config_as_cty_test.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-and-test
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (1)
config/config_as_cty_test.go (1)

255-255:

❓ Verification inconclusive

Key change: Access to locals map uses "local" instead of "locals"

The change updates the key used to access the locals map in the stack configuration. This adjustment likely aligns with the actual structure of the parsed stack configuration file. Ensure that this change is consistent with the HCL parsing expectations for stack configurations.

Let's verify this change is consistent with the actual structure of the stack configuration file:


🏁 Script executed:

#!/bin/bash
# Check the structure of the stack configuration file
cat ../test/fixtures/stacks/locals/live/terragrunt.stack.hcl | grep -A 10 "local"

Length of output: 170


Action Required: Manually verify the key name in the stack configuration file

  • The update in config/config_as_cty_test.go changes the access from stackMap["locals"] to stackMap["local"]; this appears to align with the intended configuration parsing.
  • The automated check failed to locate the file at ../test/fixtures/stacks/locals/live/terragrunt.stack.hcl. This may be due to an incorrect file path or a change in the test fixtures’ directory structure.
  • Please confirm manually (or update the file search command) that the stack configuration file uses the key "local".
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@denis256 denis256 marked this pull request as ready for review March 24, 2025 18:05
@denis256 denis256 requested review from lev-ok and yhakbar as code owners March 24, 2025 18:05
yhakbar
yhakbar previously approved these changes Mar 24, 2025
@yhakbar
Copy link
Collaborator

yhakbar commented Mar 24, 2025

@denis256 this is good, but it doesn't actually validate that the unit has a terragrunt.hcl file in it or that a stack has a terragrunt.stack.hcl file in it, right?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
internal/worker/worker.go (4)

1-19: Great package-level documentation; consider adding an example use case for clarity.

These doc comments are detailed and outline the functionality well. However, adding a minimal code snippet demonstrating usage would help new users quickly grasp how to integrate and run tasks with this worker pool.


29-46: Consider unifying concurrency handling for isRunning and isStopping.

Currently, isStopping is managed by an atomic.Bool, while isRunning is protected by an RWMutex. Mixing approaches can introduce complexity. Consolidating both fields under either an atomic or a mutex-based approach might simplify the code and reduce potential confusion. For instance, you could do:

- isRunning   bool
+ isRunning   atomic.Bool

Then remove or adapt the associated locks accordingly where isRunning is updated.


95-119: Consider streamlining error storage to avoid duplication.

Currently, errors are appended to both wp.allErrors and wp.errorsSlice. This maintains backward compatibility but creates overhead. If possible, refactor to rely solely on wp.allErrors and derive any slice representations on-demand.


190-216: Stop() is asynchronous; clarify or rename to better reflect its behavior.

Because Stop() returns immediately, concurrency newcomers might expect it to block. Consider documenting that it initiates a shutdown and proceeds asynchronously, or rename it (e.g., StopAsync) to reduce confusion. You could also add something like:

-// Stop shuts down the worker pool after current tasks are completed
+// Stop initiates a shutdown and returns immediately, without blocking for in-flight tasks.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eec827e and aa99b8b.

📒 Files selected for processing (1)
  • internal/worker/worker.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • internal/worker/worker.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build-and-test
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (4)
internal/worker/worker.go (4)

48-63: Boundary handling for zero or negative workers looks good.

Automatically elevating maxWorkers to 1 if a non-positive value is provided prevents unforeseen panics and ensures a functional pool. This approach appears solid for most use cases.


65-93: Channel re-initialization logic in Start() is concise and correct.

Recreating channels and clearing errors upon restart prevents lingering state or stale data from a previous run.


132-174: Submit() respects previous feedback on RWLock usage.

This code now uses RLock to guard isRunning, addressing the earlier suggestion by yhakbar regarding potential efficiency gains.


218-237: GracefulStop() correctly completes all tasks before shutting down.

This blocking approach is well-structured, ensuring the pool finalizes work properly and avoids channel panics.

@denis256 denis256 requested a review from yhakbar March 26, 2025 21:14
@denis256 denis256 changed the title Stack validation improvements feat: stack validation improvements Mar 26, 2025
yhakbar
yhakbar previously approved these changes Mar 27, 2025
@denis256 denis256 enabled auto-merge (squash) March 28, 2025 13:59
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
docs/_docs/04_reference/02-cli-options.md (1)

359-365: Enhance Clarity of the Stack Validation Section

The new bullet clearly explains that during stack generation Terragrunt validates that each unit’s directory contains a terragrunt.hcl file and that each stack’s directory contains a terragrunt.stack.hcl file. However, the flow could be improved for better readability and consistency with the rest of the documentation. For example, consider rephrasing the section to explicitly mention Terragrunt and tighten the language. A suggested diff is provided below:

- - Validation of Units and Stacks: During the stack generation, the system will validate that each unit and stack's target directory contains the appropriate configuration file (`terragrunt.hcl` for units and `terragrunt.stack.hcl` for stacks). This ensures the directories are correctly structured before proceeding with the stack generation.  
-   To **skip this validation**, you can use the `--no-stack-validate` flag:
-   
- ```bash
- terragrunt stack generate --no-stack-validate
- ```
+ - **Validation of Units and Stacks**: During stack generation, Terragrunt validates that each unit’s target directory contains a `terragrunt.hcl` file and that each stack’s target directory contains a `terragrunt.stack.hcl` file. This check ensures the directory structure is correct before proceeding.
+   To skip this validation, use the `--no-stack-validate` flag:
+   
+   ```bash
+   terragrunt stack generate --no-stack-validate
+   ```

This minor rewording improves clarity and aligns the description with the overall documentation style.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aa99b8b and 6f8b68f.

📒 Files selected for processing (3)
  • config/config.go (0 hunks)
  • docs/_docs/04_reference/02-cli-options.md (1 hunks)
  • options/options.go (2 hunks)
💤 Files with no reviewable changes (1)
  • config/config.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • options/options.go
🧰 Additional context used
📓 Path-based instructions (1)
`docs/**/*.md`: Review the documentation for clarity, grammar, and spelling. Make sure that the documentation is easy to understand and follow. There is currently a migration under...

docs/**/*.md: Review the documentation for clarity, grammar, and spelling. Make sure that the documentation is easy to understand and follow. There is currently a migration underway from the Jekyll based documentation in docs to the Starlight + Astro based documentation in docs-starlight. Whenever changes are made to the docs directory, ensure that an equivalent change is made in the docs-starlight directory to keep the docs-starlight documentation accurate.

  • docs/_docs/04_reference/02-cli-options.md
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Pull Request has non-contributor approval
  • GitHub Check: Pull Request has non-contributor approval
  • GitHub Check: build-and-test

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
test/fixtures/stacks/errors/cycles/live/terragrunt.stack.hcl (1)

1-4: Clear and Concise Stack Declaration:
The consolidation into a single "stack" declaration simplifies the configuration and aligns with the intended validation improvements. The use of the expression ${get_repo_root()}/stack in the source value promotes portability across test environments. Please confirm that the helper function get_repo_root() is defined and available in your testing context, ensuring it returns the correct repository root path. Additionally, verify that the integration tests fully exercise this configuration scenario to catch any missing validations (e.g., ensuring that a terragrunt.stack.hcl file is indeed detected as expected).

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4b410a and 1d1ea9b.

📒 Files selected for processing (2)
  • test/fixtures/stacks/errors/cycles/live/terragrunt.stack.hcl (1 hunks)
  • test/fixtures/stacks/errors/cycles/stack/terragrunt.stack.hcl (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test/fixtures/stacks/errors/cycles/stack/terragrunt.stack.hcl
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unessential
  • GitHub Check: build-and-test
  • GitHub Check: Pull Request has non-contributor approval

@denis256 denis256 merged commit 9f9929a into main Mar 28, 2025
8 of 9 checks passed
@denis256 denis256 deleted the tg-988 branch March 28, 2025 15:11
@coderabbitai coderabbitai bot mentioned this pull request May 22, 2025
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants