Files
PandeyandGitHub 09b16ec619 refactor(foundryctl): silent-by-default logs, typed exit codes, ban fmt.Errorf (#118)
## Summary

Reshape foundryctl's output contract so it composes with agents and
shell pipelines. Three changes that fall out of the same observation:
**stdout, stderr, and exit codes should be a stable contract — today
they're conflated.**

- **Logger to stderr, silent by default.** `instrumentation.NewLogger`
writes to `os.Stderr` (was `os.Stdout`) and uses `slog.DiscardHandler`
unless `--debug` is set. Matches helm/aws CLI convention. stdout is now
reserved for command results.
- **Typed exit codes.** `internal/errors.typ` carries a `code int`
field; `errors.ExitCode(err)` walks the wrap chain via `errors.As` and
returns a deterministic code: `InvalidInput=2, NotFound=3,
Unsupported=4, Internal=5, Fatal=6`, untyped=1, nil=0. Compact 1-6
scheme rather than sysexits.h because sysexits would collapse `Internal`
and `Fatal` into the same `EX_SOFTWARE (70)`, losing a distinction we
care about (Fatal = recovered panic; Internal = expected-but-failed
path). `cmd/foundryctl/main.go` now exits with `errors.ExitCode(err)`.
- **`fmt.Errorf` forbidden by lint.** New forbidigo rules in
`.golangci.yml` ban `fmt.Errorf` and `fmt.Print*` / `print` / `println`.
168 call sites across 38 files converted to `errors.Newf` /
`errors.Wrapf` with contextually-chosen types. Narrow exception for
`internal/errors/error_test.go` so the ExitCode wrap-chain test stays
authentic.

Sites of note for review:
- `internal/errors/type.go` — exit code mapping table (one source of
truth)
- `internal/errors/error.go` — `ExitCode(err)` helper
- `internal/instrumentation/logger.go` — `slog.DiscardHandler` default
- `.golangci.yml` — forbidigo config + the single narrow test exclusion

## Test plan

- [x] `go build ./...`
- [x] `go test ./...` (all packages pass; new `TestExitCode` covers 9
cases: nil, untyped, each typed, fmt.Errorf-wrapped,
foundry-Wrapf-wrapped)
- [x] `golangci-lint run ./...` — 0 issues
- [x] Manual: `foundryctl forge` on a missing file exits non-zero and
emits nothing on stdout (logs hidden); `--debug` emits JSON on stderr
only
- [x] Manual: end-to-end forge + cast against the docker/compose flavor
still produces a healthy stack
2026-05-17 23:01:00 +05:30

131 lines
4.1 KiB
Go

package terraform
import (
"context"
"log/slog"
"os/exec"
"path/filepath"
"github.com/signoz/foundry/api/v1alpha1"
"github.com/signoz/foundry/api/v1alpha1/installation"
"github.com/signoz/foundry/internal/domain"
"github.com/signoz/foundry/internal/errors"
"github.com/signoz/foundry/internal/infrastructure"
)
var _ infrastructure.Generator = (*Generator)(nil)
const infrastructureDir = "infrastructure"
// Generator generates Terraform manifests for infrastructure deployment.
type Generator struct {
logger *slog.Logger
}
type templateData struct {
installation.Casting
Provider v1alpha1.Platform
ComputeType infrastructure.ComputeType
}
// New creates a new Terraform Generator.
func New(logger *slog.Logger) *Generator {
return &Generator{
logger: logger,
}
}
// Generate creates Terraform manifests based on the casting configuration.
// The compute type is resolved automatically from the provider and deployment mode.
func (g *Generator) Generate(ctx context.Context, config installation.Casting) ([]domain.Material, error) {
if !config.Spec.Infrastructure.Enabled {
return nil, nil
}
provider, err := infrastructure.ResolveProvider(config.Spec.Deployment.Platform)
if err != nil {
return nil, err
}
computeType, err := infrastructure.ResolveComputeType(provider, config.Spec.Deployment)
if err != nil {
return nil, err
}
g.logger.InfoContext(ctx, "generating terraform manifests",
slog.String("provider", provider.String()),
slog.String("computeType", computeType.String()),
)
data := templateData{
Casting: config,
Provider: provider,
ComputeType: computeType,
}
mainTemplate, varsTemplate, outputsTemplate, err := g.templatesFor(provider, computeType)
if err != nil {
return nil, err
}
materials := make([]domain.Material, 0, 4)
for _, item := range []struct {
tmpl *domain.Template
path string
}{
{mainTemplate, "main.tf.json"},
{varsTemplate, "variables.tf.json"},
{providersTFTemplate, "providers.tf.json"},
{outputsTemplate, "outputs.tf.json"},
} {
m, err := item.tmpl.Render(data, filepath.Join(infrastructureDir, item.path))
if err != nil {
return nil, errors.Wrapf(err, errors.TypeInternal, "failed to render %s", item.path)
}
materials = append(materials, m)
}
return materials, nil
}
// Validate runs `terraform validate` against the manifests in poursPath/infrastructure.
func (g *Generator) Validate(ctx context.Context, poursPath string) error {
infraDir := filepath.Join(poursPath, infrastructureDir)
g.logger.InfoContext(ctx, "validating terraform manifests", slog.String("path", infraDir))
cmd := exec.CommandContext(ctx, "terraform", "validate")
cmd.Dir = infraDir
out, err := cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, errors.TypeInternal, "terraform validate failed\n%s", out)
}
return nil
}
// templatesFor returns the provider+compute-type specific templates.
func (g *Generator) templatesFor(provider v1alpha1.Platform, computeType infrastructure.ComputeType) (main, vars, outputs *domain.Template, err error) {
switch provider {
case v1alpha1.PlatformAWS:
switch computeType {
case infrastructure.ComputeTypeEC2:
return awsEC2MainTFTemplate, awsEC2VariablesTFTemplate, awsEC2OutputsTFTemplate, nil
case infrastructure.ComputeTypeEKS:
return awsEKSMainTFTemplate, awsEKSVariablesTFTemplate, awsEKSOutputsTFTemplate, nil
}
case v1alpha1.PlatformGCP:
switch computeType {
case infrastructure.ComputeTypeGCE:
return gcpGCEMainTFTemplate, gcpGCEVariablesTFTemplate, gcpGCEOutputsTFTemplate, nil
case infrastructure.ComputeTypeGKE:
return gcpGKEMainTFTemplate, gcpGKEVariablesTFTemplate, gcpGKEOutputsTFTemplate, nil
}
case v1alpha1.PlatformAzure:
switch computeType {
case infrastructure.ComputeTypeVM:
return azureVMMainTFTemplate, azureVMVariablesTFTemplate, azureVMOutputsTFTemplate, nil
case infrastructure.ComputeTypeAKS:
return azureAKSMainTFTemplate, azureAKSVariablesTFTemplate, azureAKSOutputsTFTemplate, nil
}
}
return nil, nil, nil, errors.Newf(errors.TypeUnsupported, "unsupported provider %q / compute type %q combination", provider, computeType)
}