Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ MONITOR_EXTRA_NAMESPACES=vault,vault-transit,longhorn-system
# METRICS_MAX_STREAMS_PER_USER=4
# METRICS_MAX_STREAMS_PER_TARGET=2

# Centralized logs are optional. Leave the URL unset to download the current
# running Pods' last 10,000 lines.
# Uncomment these settings to enable Loki locally.
# LOGGING_QUERY_URL=http://127.0.0.1:3100
# LOGGING_QUERY_TIMEOUT=5m

# Workload placement ships complete but activates in three operational gates:
# disabled (labels/reports only), canary (listed numeric setup-session IDs),
# then enabled. Changing modes does not require a different build.
Expand Down
13 changes: 12 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,15 @@ VAULT_PORT ?= 8200
METRICS_PORT ?= 9091
METRICS_NAMESPACE ?= monitoring
METRICS_SERVICE ?= thanos-query
LOGGING_PORT ?= 3100
LOGGING_NAMESPACE ?= logging
LOGGING_SERVICE ?= loki-gateway
DEV_API_BASE ?= http://localhost:8080
DEV_WALLET_SEED_FILE ?= .dev/keyring-wallet.seed

.PHONY: build test check-pg-image gen-keypair gen-farm-key dev-claim dev-keyring-sign-in tidy dev dev-placement \
migrate migrate-down migrate-new enroll enroll-prod \
deploy-db forward-db forward-vault forward-metrics \
deploy-db forward-db forward-vault forward-metrics forward-logging \
image-build image-push \
release release-check release-image release-chart release-github \
deploy
Expand Down Expand Up @@ -167,6 +170,14 @@ forward-metrics:
sleep 2; \
done

forward-logging:
@echo "Forwarding $(DEV_CONTEXT) $(LOGGING_NAMESPACE)/svc/$(LOGGING_SERVICE) → localhost:$(LOGGING_PORT) (Ctrl-C to stop)"
@trap 'exit 0' INT; while true; do \
kubectl --context $(DEV_CONTEXT) port-forward -n $(LOGGING_NAMESPACE) svc/$(LOGGING_SERVICE) $(LOGGING_PORT):80 || true; \
echo "port-forward dropped — reconnecting in 2s"; \
sleep 2; \
done

# ─── GHCR ─────────────────────────────────────────────────────────────────────
image-build:
docker build --platform $(PLATFORM) -t $(IMAGE):$(TAG) .
Expand Down
2 changes: 2 additions & 0 deletions helm/vtafarm-api/templates/vtafarm-api/configmap.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ data:
METRICS_MAX_POINTS: {{ .Values.metrics.maxPoints | quote }}
METRICS_MAX_STREAMS_PER_USER: {{ .Values.metrics.maxStreamsPerUser | quote }}
METRICS_MAX_STREAMS_PER_TARGET: {{ .Values.metrics.maxStreamsPerTarget | quote }}
LOGGING_QUERY_URL: {{ .Values.logging.queryURL | quote }}
LOGGING_QUERY_TIMEOUT: {{ .Values.logging.queryTimeout | quote }}
PLACEMENT_MODE: {{ .Values.placement.mode | quote }}
PLACEMENT_CANARY_SESSION_IDS: {{ .Values.placement.canarySessionIDs | quote }}
PLACEMENT_GREEN_BELOW_PCT: {{ .Values.placement.greenBelowPct | quote }}
Expand Down
4 changes: 4 additions & 0 deletions helm/vtafarm-api/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ metrics:
maxStreamsPerUser: "4"
maxStreamsPerTarget: "2"

logging:
queryURL: ""
queryTimeout: "5m"

placement:
mode: disabled
canarySessionIDs: ""
Expand Down
10 changes: 10 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ type Config struct {
Monitor MonitorConfig
Placement PlacementConfig
Metrics MetricsConfig
Logging LoggingConfig
}

type MetricsConfig struct {
Expand All @@ -60,6 +61,11 @@ type MetricsConfig struct {
MaxStreamsPerTarget int
}

type LoggingConfig struct {
QueryURL string
QueryTimeout time.Duration
}

const (
PlacementDisabled = "disabled"
PlacementCanary = "canary"
Expand Down Expand Up @@ -290,6 +296,10 @@ func Load() *Config {
MaxStreamsPerUser: getEnvInt("METRICS_MAX_STREAMS_PER_USER", 4),
MaxStreamsPerTarget: getEnvInt("METRICS_MAX_STREAMS_PER_TARGET", 2),
},
Logging: LoggingConfig{
QueryURL: getEnv("LOGGING_QUERY_URL", ""),
QueryTimeout: getEnvDuration("LOGGING_QUERY_TIMEOUT", 5*time.Minute),
},
Vault: VaultConfig{
Addr: getEnv("VAULT_ADDR", ""),
VTAAddr: getEnv("VAULT_VTA_ADDR", "https://vault.vault.svc:8200"),
Expand Down
13 changes: 7 additions & 6 deletions internal/handler/admin_platform_stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,12 +337,13 @@ func (h *SetupHandler) GetPlatformStack(c *gin.Context) {
}

resp := gin.H{
"exists": true,
"id": session.VtaName,
"status": session.Status,
"label": session.VtaName,
"domain": domain.Domain,
"urls": platformURLs(&session),
"exists": true,
"id": session.VtaName,
"status": session.Status,
"label": session.VtaName,
"domain": domain.Domain,
"log_source": h.logSource(),
"urls": platformURLs(&session),
// vta_did is what the admin feeds to `pnm setup` locally to mint the
// admin DID this stack parks waiting for — so the page can't ask for
// that DID without showing this one first.
Expand Down
5 changes: 5 additions & 0 deletions internal/handler/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/ic3software/vtafarm-api/internal/didhosting"
"github.com/ic3software/vtafarm-api/internal/ghcr"
"github.com/ic3software/vtafarm-api/internal/k8s"
"github.com/ic3software/vtafarm-api/internal/logquery"
"github.com/ic3software/vtafarm-api/internal/middleware"
"github.com/ic3software/vtafarm-api/internal/model"
"github.com/ic3software/vtafarm-api/internal/setup"
Expand All @@ -34,6 +35,7 @@ type SetupHandler struct {
// authenticates with vtafarm-api's own client keypair.
didHosting *didhosting.Factory // nil when no keypair configured
k8s *k8s.Client
logquery *logquery.Client
resources deploymentResourceObserver
orch *setup.Orchestrator
ghcr *ghcr.Client // nil when not configured
Expand All @@ -53,6 +55,7 @@ func NewSetupHandler(
appEnv, ingressIP, clusterDomain string,
dhFactory *didhosting.Factory,
k8sClient *k8s.Client,
logqueryClient *logquery.Client,
orch *setup.Orchestrator,
ghcrClient *ghcr.Client,
mediatorGhcrClient *ghcr.Client,
Expand All @@ -67,6 +70,7 @@ func NewSetupHandler(
clusterDomain: clusterDomain,
didHosting: dhFactory,
k8s: k8sClient,
logquery: logqueryClient,
resources: k8sClient,
orch: orch,
ghcr: ghcrClient,
Expand Down Expand Up @@ -780,6 +784,7 @@ func (h *SetupHandler) Get(c *gin.Context) {
"id": session.VtaName,
"status": session.Status,
"mode": session.Mode,
"log_source": h.logSource(),
"domain_type": session.DomainType,
"domain": session.Domain,
"url": session.PublicURL(),
Expand Down
198 changes: 196 additions & 2 deletions internal/handler/setup_export.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,29 @@ import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"

"github.com/gin-gonic/gin"

"github.com/ic3software/vtafarm-api/internal/metrics"
"github.com/ic3software/vtafarm-api/internal/model"
)

const exportLogTailLines = 10000

const (
logSourceRetained = "retained"
logSourceKubernetes = "kubernetes"
)

// The mediator's config sits under conf/; every other component's is at the
// mount root (docs/full-stack-setup-design.md §"Path ownership").
type exportComponent struct {
Expand Down Expand Up @@ -52,7 +63,7 @@ func (h *SetupHandler) ExportConfigs(c *gin.Context) {
// GET /api/v1/setup/:id/export/logs
func (h *SetupHandler) ExportLogs(c *gin.Context) {
if s := h.userSession(c); s != nil {
h.exportArchive(c, s, exportKindLogs)
h.exportRetainedLogs(c, s, false)
}
}

Expand All @@ -66,7 +77,7 @@ func (h *SetupHandler) AdminExportConfigs(c *gin.Context) {
// AdminExportLogs — GET /api/v1/admin/setup-sessions/:id/export/logs.
func (h *SetupHandler) AdminExportLogs(c *gin.Context) {
if s := h.adminSession(c); s != nil {
h.exportArchive(c, s, exportKindLogs)
h.exportRetainedLogs(c, s, true)
}
}

Expand Down Expand Up @@ -158,3 +169,186 @@ func (h *SetupHandler) exportOne(ctx context.Context, ns string, comp exportComp
}
return comp.name + "-config.toml", body, nil
}

type logExportManifest struct {
RetentionDays int `json:"retention_days"`
RangeDays int `json:"range_days"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
Entries int `json:"entries"`
}

type retainedLogFile struct {
name string
path string
}

func (h *SetupHandler) exportRetainedLogs(c *gin.Context, session *model.SetupSession, admin bool) {
var owner model.User
if err := h.db.WithContext(c.Request.Context()).First(&owner, session.UserID).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load log retention entitlement"})
return
}
end := time.Now().UTC()
entitlement := logExportEntitlement(owner, admin)
rangeDays, err := requestedLogRange(c.Query("range"), entitlement.RetentionDays)
if errors.Is(err, errLogRangeLimit) {
c.JSON(http.StatusForbidden, gin.H{"error": err.Error(), "code": "retention_limit"})
return
}
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if h.logquery == nil {
c.Header("X-Log-Source", logSourceKubernetes)
h.exportArchive(c, session, exportKindLogs)
return
}
if h.k8s == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "logging backend is not configured"})
return
}
start := logExportStart(session.CreatedAt, end, rangeDays)

ns := h.k8s.UserNamespace(strconv.FormatUint(uint64(session.UserID), 10))
components := exportComponents(session)
logFiles := make([]retainedLogFile, 0, len(components))
defer func() {
for _, file := range logFiles {
os.Remove(file.path)
}
}()
entries := 0
for _, comp := range components {
logsFile, err := os.CreateTemp("", "vtafarm-session-"+comp.name+"-*.log")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare log export"})
return
}
logFiles = append(logFiles, retainedLogFile{name: comp.name + ".log", path: logsFile.Name()})
query := componentLogQuery(ns, session, comp)
count, queryErr := h.logquery.WriteRange(c.Request.Context(), query, start, end, logsFile)
closeErr := logsFile.Close()
if queryErr != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": queryErr.Error()})
return
}
if closeErr != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to finalize log export"})
return
}
entries += count
}

archive, err := os.CreateTemp("", "vtafarm-session-logs-*.zip")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare log archive"})
return
}
archivePath := archive.Name()
defer os.Remove(archivePath)
manifest := logExportManifest{
RetentionDays: entitlement.RetentionDays,
RangeDays: rangeDays, Start: start, End: end, Entries: entries,
}
if err := writeRetainedLogArchive(archive, logFiles, manifest); err != nil {
archive.Close()
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to build log archive"})
return
}
if err := archive.Close(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to finalize log archive"})
return
}

c.Header("X-Log-Retention-Days", strconv.Itoa(entitlement.RetentionDays))
c.Header("X-Log-Range-Days", strconv.Itoa(rangeDays))
c.Header("X-Log-Source", logSourceRetained)
filename := fmt.Sprintf("%s-logs-%s.zip", session.VtaName, end.Format("20060102-150405"))
c.FileAttachment(archivePath, filename)
}

func (h *SetupHandler) logSource() string {
if h.logquery == nil {
return logSourceKubernetes
}
return logSourceRetained
}

func logExportEntitlement(owner model.User, admin bool) metrics.Entitlement {
entitlement := metrics.EntitlementFor(owner)
if admin {
entitlement = metrics.Entitlement{Plan: "premium", RetentionDays: metrics.PremiumRetentionDays}
}
return entitlement
}

var errLogRangeLimit = errors.New("requested log range exceeds plan retention")

func requestedLogRange(preset string, maxDays int) (int, error) {
if preset == "" {
return maxDays, nil
}
daysByPreset := map[string]int{"1d": 1, "7d": 7, "30d": 30}
days, ok := daysByPreset[preset]
if !ok {
return 0, fmt.Errorf("range must be 1d, 7d, or 30d")
}
if days > maxDays {
return 0, errLogRangeLimit
}
return days, nil
}

func logExportStart(sessionCreated, end time.Time, rangeDays int) time.Time {
start := end.Add(-time.Duration(rangeDays) * 24 * time.Hour)
if sessionCreated.After(start) {
start = sessionCreated.UTC()
}
return start
}

func componentLogQuery(namespace string, session *model.SetupSession, comp exportComponent) string {
app := "vta"
if session.IsFullStack() {
app = "fs-" + comp.name
}
return fmt.Sprintf(`{namespace=%s, app=%s} | session_id=%s`,
strconv.Quote(namespace), strconv.Quote(app), strconv.Quote(strconv.FormatUint(uint64(session.ID), 10)))
}

func writeRetainedLogArchive(dst *os.File, logFiles []retainedLogFile, manifest logExportManifest) (err error) {
zw := zip.NewWriter(dst)
defer func() {
if closeErr := zw.Close(); err == nil {
err = closeErr
}
}()
for _, file := range logFiles {
logs, openErr := os.Open(file.path)
if openErr != nil {
return openErr
}
member, createErr := zw.Create(file.name)
if createErr == nil {
_, createErr = io.Copy(member, logs)
}
logs.Close()
if createErr != nil {
return createErr
}
}
manifestMember, err := zw.Create("manifest.json")
if err != nil {
return err
}
encoded, err := json.MarshalIndent(manifest, "", " ")
if err == nil {
_, err = manifestMember.Write(append(encoded, '\n'))
}
if err != nil {
return err
}
return nil
}
Loading