dashboard

package
v0.0.0-...-1ea2549 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 43 Imported by: 0

Documentation

Overview

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides API endpoints for the local dashboard.

Package dashboard provides health streaming capabilities for the dashboard.

Package dashboard provides API endpoints for log source mode management.

Package dashboard provides a web-based user interface for monitoring and managing services.

Index

Constants

View Source
const (
	ErrorCodeAuthExpired  = "AUTH_EXPIRED"
	ErrorCodeAuthRequired = "AUTH_REQUIRED"
	ErrorCodeNotDeployed  = "NOT_DEPLOYED"
	ErrorCodeNoWorkspace  = "NO_WORKSPACE"
	ErrorCodeNoPermission = "NO_PERMISSION"
	ErrorCodeUnknown      = "UNKNOWN"
)

Azure Logs error codes

View Source
const (
	// Workspace/Service status values
	StatusNotDeployed   = "not-deployed"
	StatusNotConfigured = "not-configured"
	StatusConfigured    = "configured"
	StatusReady         = "ready"
	StatusPartial       = "partial"
	StatusMissing       = "missing"
	StatusError         = "error"
	StatusComplete      = "complete"
	StatusIncomplete    = "incomplete"

	// Auth status values
	StatusAuthenticated    = "authenticated"
	StatusUnauthenticated  = "unauthenticated"
	StatusPermissionDenied = "permission-denied"

	// Setup categories
	CategoryWorkspace          = "workspace"
	CategoryAuth               = "auth"
	CategoryDiagnosticSettings = "diagnostic-settings"
	CategoryConfig             = "config"

	// Common messages
	MsgWorkspaceNotConfigured = "Log Analytics workspace not configured"
	MsgAzureCredsNotAvailable = "Azure credentials not available. Run 'azd auth login' to authenticate."
	MsgAuthFailed             = "Authentication failed or expired. Run 'azd auth login' to re-authenticate."

	// Setup steps
	StepWorkspace          = "workspace"
	StepAuthentication     = "authentication"
	StepDiagnosticSettings = "diagnostic-settings"
	StepVerification       = "verification"
)

Azure setup status constants

Variables

This section is empty.

Functions

func BadRequest

func BadRequest(w http.ResponseWriter, message string, err error)

BadRequest writes a 400 Bad Request error response with a custom message.

func GetDashboardPort

func GetDashboardPort(ctx context.Context, projectDir string) int

GetDashboardPort returns the dashboard port for a project, or 0 if not running.

func HandleLoadError

func HandleLoadError(w http.ResponseWriter, err error)

HandleLoadError writes a standardized error response for azure.yaml load failures. This eliminates duplicate error handling code across handlers.

func HandleSaveError

func HandleSaveError(w http.ResponseWriter, err error)

HandleSaveError writes a standardized error response for azure.yaml save failures. This eliminates duplicate error handling code across handlers.

func InternalError

func InternalError(w http.ResponseWriter, message string, err error)

InternalError writes a 500 Internal Server Error response with a custom message.

func IsDashboardRunning

func IsDashboardRunning(ctx context.Context, projectDir string) bool

IsDashboardRunning checks if a dashboard is running for the given project.

func MethodGuard

func MethodGuard(handler http.HandlerFunc, allowedMethods ...string) http.HandlerFunc

MethodGuard is a middleware that validates HTTP methods for a handler. It returns a wrapped handler that only allows the specified methods. If the request method doesn't match any allowed methods, it returns 405 Method Not Allowed.

Example usage:

http.HandleFunc("/api/resource", MethodGuard(handler, http.MethodGet, http.MethodPost))

func NotFound

func NotFound(w http.ResponseWriter, message string)

NotFound writes a 404 Not Found error response with a custom message.

func ReadJSONBody

func ReadJSONBody(w http.ResponseWriter, r *http.Request, target interface{}, maxSize int64) bool

ReadJSONBody reads and decodes a JSON request body with size limits. Returns an error if the body is too large, cannot be read, or contains invalid JSON.

func RequireQueryParam

func RequireQueryParam(w http.ResponseWriter, r *http.Request, paramName string) (string, bool)

RequireQueryParam checks if a required query parameter is present and non-empty. If missing, writes a 400 Bad Request error and returns false. If present, returns true and the caller should continue processing.

func WriteJSONCreated

func WriteJSONCreated(w http.ResponseWriter, data interface{})

WriteJSONCreated writes a successful JSON response with 201 Created status.

func WriteJSONSuccess

func WriteJSONSuccess(w http.ResponseWriter, data interface{})

WriteJSONSuccess writes a successful JSON response with 200 OK status.

func WriteNoContent

func WriteNoContent(w http.ResponseWriter)

WriteNoContent writes a 204 No Content response.

Types

type AuthState

type AuthState struct {
	Status                string   `json:"status"`                  // "authenticated" | "unauthenticated" | "permission-denied" | "error"
	Message               string   `json:"message"`                 // Human-readable status message
	Principal             string   `json:"principal,omitempty"`     // Authenticated principal (email/identity)
	HasArmAccess          bool     `json:"hasArmAccess"`            // Has Azure Resource Manager access
	HasLogsAccess         bool     `json:"hasLogsAccess"`           // Has Log Analytics API access
	HasLogAnalyticsReader bool     `json:"hasLogAnalyticsReader"`   // Has Log Analytics Reader role or equivalent
	MissingScopes         []string `json:"missingScopes,omitempty"` // Missing permission scopes
}

AuthState represents the authentication and permissions state.

type AzureLogsResponse

type AzureLogsResponse struct {
	Status    string             `json:"status"`          // "ok" | "error"
	Logs      []service.LogEntry `json:"logs,omitempty"`  // Log entries
	Count     int                `json:"count"`           // Number of logs returned
	Timestamp time.Time          `json:"timestamp"`       // Response timestamp
	Error     *ErrorInfo         `json:"error,omitempty"` // Error details if status=error
}

AzureLogsResponse represents the structured response for Azure logs.

type AzureQueryResponse

type AzureQueryResponse struct {
	Service      string `json:"service"`
	ResourceType string `json:"resourceType"`
	Query        string `json:"query"`
}

AzureQueryResponse represents the KQL query used for a service.

type AzureServicesResponse

type AzureServicesResponse struct {
	Services []string `json:"services"`
}

AzureServicesResponse represents the list of available services.

type BehaviorPreferences

type BehaviorPreferences struct {
	AutoScroll      bool   `json:"autoScroll"`
	PauseOnScroll   bool   `json:"pauseOnScroll"`
	TimestampFormat string `json:"timestampFormat"`
}

BehaviorPreferences represents behavior-related preferences

type ClassificationsResponse

type ClassificationsResponse struct {
	Classifications []service.LogClassification `json:"classifications"`
}

ClassificationsResponse is the API response for GET /api/logs/classifications

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides methods to query the dashboard API.

func NewClient

func NewClient(ctx context.Context, projectDir string) (*Client, error)

NewClient creates a new dashboard API client for the given project directory. Returns nil if the dashboard is not running for this project. It first tries azdconfig (gRPC), then falls back to reading ~/.azd/config.json directly.

func NewClientWithPort

func NewClientWithPort(port int) *Client

NewClientWithPort creates a new dashboard API client for a known port.

func (*Client) GetAzureLogs

func (c *Client) GetAzureLogs(ctx context.Context, services []string, tail int, since time.Time) ([]service.LogEntry, error)

GetAzureLogs retrieves Azure logs from the dashboard's /api/azure/logs endpoint. The services parameter filters logs to specific services (nil for all services). The tail parameter limits the number of logs returned. The since parameter filters logs to those after the specified time.

func (*Client) GetAzureStatus

func (c *Client) GetAzureStatus(ctx context.Context) (*service.AzureStatus, error)

GetAzureStatus retrieves the Azure connection status from the dashboard. Checks if Azure logging is configured in azure.yaml.

func (*Client) GetServices

func (c *Client) GetServices(ctx context.Context) ([]*serviceinfo.ServiceInfo, error)

GetServices returns the list of services from the dashboard.

func (*Client) GetWebSocketURL

func (c *Client) GetWebSocketURL() string

GetWebSocketURL returns the WebSocket URL for the dashboard.

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping checks if the dashboard is running and responsive.

func (*Client) StopAllServices

func (c *Client) StopAllServices(ctx context.Context) error

StopAllServices requests the dashboard to stop all services.

func (*Client) StopService

func (c *Client) StopService(ctx context.Context, serviceName string) error

StopService requests the dashboard to stop a specific service.

func (*Client) StreamAzureLogs

func (c *Client) StreamAzureLogs(ctx context.Context, logs chan<- service.LogEntry) error

StreamAzureLogs connects to the dashboard's Azure log stream via WebSocket. The function blocks until the context is cancelled or an error occurs.

func (*Client) StreamLogs

func (c *Client) StreamLogs(ctx context.Context, serviceName string, logs chan<- service.LogEntry) error

StreamLogs connects to the dashboard's log stream via WebSocket and sends log entries to the provided channel. The serviceName parameter filters logs to a specific service (empty string for all services). The function blocks until the context is cancelled or an error occurs. The caller is responsible for closing the logs channel after StreamLogs returns.

type CopyPreferences

type CopyPreferences struct {
	DefaultFormat    string `json:"defaultFormat"` // "plaintext", "json", "markdown", "csv"
	IncludeTimestamp bool   `json:"includeTimestamp"`
	IncludeService   bool   `json:"includeService"`
}

CopyPreferences represents copy-related preferences

type EnableAzureResponse

type EnableAzureResponse struct {
	Enabled bool   `json:"enabled"`
	Message string `json:"message"`
}

EnableAzureResponse represents the response from enabling Azure logging.

type ErrorInfo

type ErrorInfo struct {
	Message string `json:"message"` // Human-readable error message
	Code    string `json:"code"`    // Error code: "AUTH_EXPIRED", "NOT_DEPLOYED", etc.
	Action  string `json:"action"`  // What the user should do
	Command string `json:"command"` // CLI command to run (optional)
	DocsURL string `json:"docsUrl"` // Documentation URL
}

ErrorInfo provides actionable error information with documentation links.

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Details string `json:"details,omitempty"`
}

ErrorResponse represents a structured error response.

type HealthChangeEvent

type HealthChangeEvent struct {
	HealthEvent
	Service   string `json:"service"`
	OldStatus string `json:"oldStatus"`
	NewStatus string `json:"newStatus"`
	Reason    string `json:"reason,omitempty"`
}

HealthChangeEvent indicates a health status change for a service.

type HealthCheck

type HealthCheck struct {
	Name    string `json:"name"`          // Check name
	Status  string `json:"status"`        // "pass" | "warn" | "fail"
	Message string `json:"message"`       // Result message
	Fix     string `json:"fix,omitempty"` // Fix instructions for failures
}

HealthCheck represents an individual health check result.

type HealthCheckResponse

type HealthCheckResponse struct {
	Status    string        `json:"status"`    // "healthy" | "degraded" | "error"
	Checks    []HealthCheck `json:"checks"`    // Individual health checks
	DocsURL   string        `json:"docsUrl"`   // Documentation URL
	Timestamp time.Time     `json:"timestamp"` // When check was performed
}

HealthCheckResponse represents the overall health check result.

type HealthEvent

type HealthEvent struct {
	Type      HealthEventType `json:"type"`
	Timestamp time.Time       `json:"timestamp"`
}

HealthEvent is the base event structure for SSE.

type HealthEventType

type HealthEventType string

HealthEventType represents the type of health event sent via SSE.

const (
	HealthEventTypeHealth    HealthEventType = "health"
	HealthEventTypeChange    HealthEventType = "health-change"
	HealthEventTypeHeartbeat HealthEventType = "heartbeat"
)

type HealthReportEvent

type HealthReportEvent struct {
	HealthEvent
	Services []healthcheck.HealthCheckResult `json:"services"`
	Summary  healthcheck.HealthSummary       `json:"summary"`
}

HealthReportEvent contains the full health report.

type HealthStreamManager

type HealthStreamManager struct {
	// contains filtered or unexported fields
}

HealthStreamManager manages health check streaming for the dashboard.

func NewHealthStreamManager

func NewHealthStreamManager(projectDir string) (*HealthStreamManager, error)

NewHealthStreamManager creates a new health stream manager.

func (*HealthStreamManager) DetectChanges

DetectChanges compares current results with previous states and returns changes.

func (*HealthStreamManager) PerformHealthCheck

func (m *HealthStreamManager) PerformHealthCheck(ctx context.Context, serviceFilter []string) (*healthcheck.HealthReport, error)

PerformHealthCheck performs a single health check and returns the report.

type HeartbeatEvent

type HeartbeatEvent struct {
	HealthEvent
}

HeartbeatEvent is a keep-alive signal.

type LogConfigResponse

type LogConfigResponse struct {
	Service      string   `json:"service"`
	Mode         string   `json:"mode"` // "tables" | "custom"
	Tables       []string `json:"tables,omitempty"`
	Query        string   `json:"query,omitempty"`
	ResourceType string   `json:"resourceType"`
}

LogConfigResponse represents the log configuration for a service.

type ModeRequest

type ModeRequest struct {
	Mode string `json:"mode"` // "local" or "azure"
}

ModeRequest represents a request to change the log source mode.

type ModeResponse

type ModeResponse struct {
	Mode              string `json:"mode"`
	AzureEnabled      bool   `json:"azureEnabled"`
	AzureStatus       string `json:"azureStatus"` // "connected", "disconnected", "error"
	AzureRealtime     bool   `json:"azureRealtime"`
	ResourceCount     int    `json:"resourceCount"`
	ConnectionIssue   string `json:"connectionIssue,omitempty"`
	ConnectionMessage string `json:"connectionMessage,omitempty"`
}

ModeResponse represents the current mode state.

type SaveLogConfigRequest

type SaveLogConfigRequest struct {
	Service string   `json:"service"`
	Mode    string   `json:"mode"` // "tables" | "custom"
	Tables  []string `json:"tables,omitempty"`
	Query   string   `json:"query,omitempty"`
}

SaveLogConfigRequest represents the request to save log configuration.

type SaveQueryRequest

type SaveQueryRequest struct {
	Service string `json:"service"`
	Query   string `json:"query"`
}

SaveQueryRequest represents the request body for saving a custom query.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents the dashboard HTTP server.

func GetServer

func GetServer(projectDir string) *Server

GetServer returns the dashboard server instance for the specified project. Creates a new instance if one doesn't exist for this project.

func (*Server) BroadcastServiceUpdate

func (s *Server) BroadcastServiceUpdate(projectDir string) error

BroadcastServiceUpdate fetches fresh service info and broadcasts to all connected clients. This is called when environment variables are updated (e.g., after azd provision). Broadcasts asynchronously with goroutine limiting to prevent resource exhaustion.

func (*Server) BroadcastUpdate

func (s *Server) BroadcastUpdate(services []*registry.ServiceRegistryEntry)

BroadcastUpdate sends service updates to all connected WebSocket clients. Broadcasts asynchronously with goroutine limiting to prevent resource exhaustion.

func (*Server) GetURL

func (s *Server) GetURL() string

GetURL returns the dashboard URL if the server is started, empty string otherwise.

func (*Server) Start

func (s *Server) Start() (string, error)

Start starts the dashboard server on an assigned port.

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the dashboard server and releases its port assignment. Safe to call multiple times - will only stop if server was successfully started.

type ServiceSetupState

type ServiceSetupState struct {
	ServiceName        string `json:"serviceName"`                // Service name from azure.yaml
	ResourceName       string `json:"resourceName,omitempty"`     // Azure resource name
	ResourceType       string `json:"resourceType,omitempty"`     // Azure resource type
	Deployed           bool   `json:"deployed"`                   // Resource exists in Azure
	DiagnosticSettings bool   `json:"diagnosticSettings"`         // Diagnostic settings configured
	LogsFlowing        bool   `json:"logsFlowing"`                // Logs are being received
	Status             string `json:"status"`                     // "ready" | "partial" | "not-configured" | "not-deployed"
	LastLogTimestamp   string `json:"lastLogTimestamp,omitempty"` // ISO timestamp of most recent log
}

ServiceSetupState represents setup state for a single service.

type SetupIssue

type SetupIssue struct {
	Severity string `json:"severity"`          // "error" | "warning" | "info"
	Category string `json:"category"`          // "workspace" | "auth" | "diagnostic-settings" | "config"
	Message  string `json:"message"`           // Issue description
	Fix      string `json:"fix"`               // Fix command or instruction
	DocsURL  string `json:"docsUrl,omitempty"` // Documentation link
}

SetupIssue represents a configuration issue with actionable fix.

type SetupStateResponse

type SetupStateResponse struct {
	Step           string              `json:"step"`           // Current setup step
	OverallStatus  string              `json:"overallStatus"`  // "complete" | "incomplete" | "error"
	Workspace      WorkspaceState      `json:"workspace"`      // Log Analytics workspace state
	Authentication AuthState           `json:"authentication"` // Authentication state
	Services       []ServiceSetupState `json:"services"`       // Per-service setup state
	Issues         []SetupIssue        `json:"issues"`         // List of issues found
	NextSteps      []string            `json:"nextSteps"`      // Recommended next actions
	Timestamp      time.Time           `json:"timestamp"`      // When state was checked
}

SetupStateResponse represents the overall Azure logs setup state.

type TableCategory

type TableCategory struct {
	Name        string   `json:"name"`
	DisplayName string   `json:"displayName"`
	Tables      []string `json:"tables"`
}

TableCategory represents a category of tables.

type TablesResponse

type TablesResponse struct {
	Tables      []azure.TableInfo `json:"tables"`
	Recommended []string          `json:"recommended"`
	Workspace   string            `json:"workspace"`
	Categories  []TableCategory   `json:"categories"`
}

TablesResponse represents the response from the tables API.

type UIPreferences

type UIPreferences struct {
	GridColumns      int      `json:"gridColumns"`
	ViewMode         string   `json:"viewMode"` // "grid" or "unified"
	SelectedServices []string `json:"selectedServices"`
}

UIPreferences represents UI-related preferences

type UserPreferences

type UserPreferences struct {
	Version  string              `json:"version"`
	UI       UIPreferences       `json:"ui"`
	Behavior BehaviorPreferences `json:"behavior"`
	Copy     CopyPreferences     `json:"copy"`
}

UserPreferences represents user preferences for the logs view

type VerifyLogsRequest

type VerifyLogsRequest struct {
	Service string `json:"service"`
}

VerifyLogsRequest represents the request body for log verification.

type VerifyLogsResponse

type VerifyLogsResponse struct {
	Success   bool                 `json:"success"`
	LogsFound int                  `json:"logsFound"`
	TimeRange *VerifyLogsTimeRange `json:"timeRange,omitempty"`
	Sample    []VerifyLogsSample   `json:"sample,omitempty"`
	Message   string               `json:"message"`
	NextSteps []string             `json:"nextSteps,omitempty"`
}

VerifyLogsResponse represents the response for log verification.

type VerifyLogsSample

type VerifyLogsSample struct {
	Timestamp string `json:"timestamp"` // ISO timestamp
	Message   string `json:"message"`
	Level     string `json:"level"`
}

VerifyLogsSample represents a sample log entry.

type VerifyLogsTimeRange

type VerifyLogsTimeRange struct {
	Start string `json:"start"` // ISO timestamp
	End   string `json:"end"`   // ISO timestamp
}

VerifyLogsTimeRange represents the time range of logs found.

type WorkspaceState

type WorkspaceState struct {
	Status      string `json:"status"`                // "configured" | "missing" | "not-deployed" | "invalid"
	WorkspaceID string `json:"workspaceId,omitempty"` // Workspace resource ID
	Message     string `json:"message"`               // Human-readable status message
	Source      string `json:"source,omitempty"`      // Where workspace ID was found (env, azure.yaml)
}

WorkspaceState represents the Log Analytics workspace configuration state.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL