Add service status and usage dashboard, refresh externally published edits
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func networkAddresses() []protocol.NetworkAddress {
|
||||
result := []protocol.NetworkAddress{}
|
||||
interfaces, _ := net.Interfaces()
|
||||
for _, iface := range interfaces {
|
||||
if iface.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
addresses, _ := iface.Addrs()
|
||||
for _, address := range addresses {
|
||||
ip, _, err := net.ParseCIDR(address.String())
|
||||
if err != nil || ip.IsUnspecified() {
|
||||
continue
|
||||
}
|
||||
text := ip.String()
|
||||
if ip.IsLinkLocalUnicast() && ip.To4() == nil {
|
||||
text += "%" + iface.Name
|
||||
}
|
||||
result = append(result, protocol.NetworkAddress{Interface: iface.Name, IP: text})
|
||||
}
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].Interface != result[j].Interface {
|
||||
return result[i].Interface < result[j].Interface
|
||||
}
|
||||
return result[i].IP < result[j].IP
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func endpointPort(u *url.URL) string {
|
||||
if port := u.Port(); port != "" {
|
||||
return port
|
||||
}
|
||||
if u.Scheme == "https" || u.Scheme == "wss" {
|
||||
return "443"
|
||||
}
|
||||
return "80"
|
||||
}
|
||||
|
||||
func candidateURLs(addresses []protocol.NetworkAddress, scheme, port, path string) []string {
|
||||
result := []string{}
|
||||
for _, address := range addresses {
|
||||
u := url.URL{Scheme: scheme, Host: net.JoinHostPort(address.IP, port), Path: path}
|
||||
result = append(result, u.String())
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func localEndpoint(u *url.URL, hostname string, addresses []protocol.NetworkAddress) bool {
|
||||
host := u.Hostname()
|
||||
if host == "localhost" || host == hostname || net.ParseIP(host).IsLoopback() {
|
||||
return true
|
||||
}
|
||||
for _, address := range addresses {
|
||||
if host == address.IP {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func systemStatus(r *http.Request, started time.Time, runErr error) *protocol.SystemStatus {
|
||||
hostname, _ := os.Hostname()
|
||||
s := &protocol.SystemStatus{Hostname: hostname, StartedAt: started.UTC().Format(time.RFC3339), Uptime: time.Since(started).Round(time.Second).String(), Addresses: networkAddresses(), Server: protocol.ServiceStatus{Health: "healthy"}, Ntfy: protocol.ServiceStatus{Health: "not configured"}, Note: "Addresses belong to the server computer (or container). Candidate URLs are not reachability checks; binding, firewalls, port mapping and TLS may differ."}
|
||||
if runErr != nil {
|
||||
s.Server.Health = "execution unavailable"
|
||||
}
|
||||
if address, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
|
||||
_, port, err := net.SplitHostPort(address.String())
|
||||
if err == nil {
|
||||
scheme := "ws"
|
||||
if r.TLS != nil {
|
||||
scheme = "wss"
|
||||
}
|
||||
s.Server.URL = (&url.URL{Scheme: scheme, Host: address.String(), Path: "/connect"}).String()
|
||||
s.Server.Port = port
|
||||
s.Server.Candidates = candidateURLs(s.Addresses, scheme, port, "/connect")
|
||||
}
|
||||
}
|
||||
endpoints := notificationEndpoints()
|
||||
if len(endpoints) == 0 {
|
||||
return s
|
||||
}
|
||||
s.Topic = endpoints[0].Topic
|
||||
s.Ntfy.Health = "not checked"
|
||||
// Only the validated public base is returned. Publishing URL and tokens
|
||||
// never leave the server, even on probe failure.
|
||||
s.Ntfy.URL = endpoints[0].ServerURL
|
||||
if u, err := url.Parse(s.Ntfy.URL); err == nil && u.Host != "" {
|
||||
s.Ntfy.Port = endpointPort(u)
|
||||
if localEndpoint(u, hostname, s.Addresses) {
|
||||
s.Ntfy.Candidates = candidateURLs(s.Addresses, u.Scheme, s.Ntfy.Port, "/"+s.Topic)
|
||||
}
|
||||
}
|
||||
publish, err := url.Parse(os.Getenv("PIPELINES_NTFY_URL"))
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
if s.Ntfy.URL == "" && localEndpoint(publish, hostname, s.Addresses) {
|
||||
s.Ntfy.Port = endpointPort(publish)
|
||||
s.Ntfy.Candidates = candidateURLs(s.Addresses, publish.Scheme, s.Ntfy.Port, "/"+s.Topic)
|
||||
}
|
||||
publish.Path = "/v1/health"
|
||||
publish.RawPath = ""
|
||||
publish.RawQuery = ""
|
||||
publish.Fragment = ""
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, publish.String(), nil)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
response, err := client.Do(req)
|
||||
s.Ntfy.Health = "unreachable"
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
defer response.Body.Close()
|
||||
s.Ntfy.Health = "unhealthy"
|
||||
var health struct {
|
||||
Healthy bool `json:"healthy"`
|
||||
}
|
||||
if response.StatusCode == http.StatusOK && json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&health) == nil && health.Healthy {
|
||||
s.Ntfy.Health = "healthy"
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"git.a-wan.net/alan/pipelines/internal/client"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStatusRPCReportsServerAndNtfyWithoutSecrets(t *testing.T) {
|
||||
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/health" {
|
||||
t.Error("unexpected probe", r.URL.Path)
|
||||
}
|
||||
w.Write([]byte(`{"healthy":true}`))
|
||||
}))
|
||||
defer ntfy.Close()
|
||||
t.Setenv("PIPELINES_NTFY_URL", ntfy.URL+"/phone")
|
||||
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", ntfy.URL)
|
||||
t.Setenv("PIPELINES_NTFY_TOKEN", "never-return-this-token")
|
||||
srv := httptest.NewServer(Handler(context.Background()))
|
||||
defer srv.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
c, err := client.Open(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
response, err := c.Call(ctx, protocol.Message{Type: protocol.GetStatus})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := response.Status
|
||||
if s == nil || s.Server.Health != "healthy" || s.Ntfy.Health != "healthy" || s.Ntfy.URL != ntfy.URL || s.Topic != "phone" || len(s.Addresses) == 0 || s.Hostname == "" || s.Server.Port == "" || s.Ntfy.Port == "" || s.StartedAt == "" || len(s.Ntfy.Candidates) == 0 {
|
||||
t.Fatal("incomplete status", s)
|
||||
}
|
||||
encoded, _ := json.Marshal(s)
|
||||
if strings.Contains(string(encoded), "never-return") {
|
||||
t.Fatal("credentials leaked", string(encoded))
|
||||
}
|
||||
if !strings.Contains(s.Server.URL, s.Server.Port) || !strings.Contains(s.Note, "not reachability checks") {
|
||||
t.Fatal("ports or safety disclaimer missing", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusUnconfiguredUnhealthyAndIPv6Candidates(t *testing.T) {
|
||||
t.Setenv("PIPELINES_NTFY_URL", "")
|
||||
t.Setenv("PIPELINES_NTFY_PUBLIC_URL", "")
|
||||
r := httptest.NewRequest("GET", "http://localhost/connect", nil)
|
||||
if s := systemStatus(r, time.Now(), nil); s.Ntfy.Health != "not configured" {
|
||||
t.Fatal(s)
|
||||
}
|
||||
for _, body := range []string{`{"healthy":false}`, `not-json`} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(body)) }))
|
||||
t.Setenv("PIPELINES_NTFY_URL", srv.URL+"/topic")
|
||||
s := systemStatus(r, time.Now(), nil)
|
||||
srv.Close()
|
||||
if s.Ntfy.Health != "unhealthy" || s.Ntfy.URL != "" || s.Ntfy.Port == "" {
|
||||
t.Fatal(s)
|
||||
}
|
||||
}
|
||||
addresses := []protocol.NetworkAddress{{Interface: "test", IP: "::1"}, {Interface: "test", IP: "192.0.2.1"}}
|
||||
urls := candidateURLs(addresses, "http", "8090", "/topic")
|
||||
if urls[0] != "http://[::1]:8090/topic" || urls[1] != "http://192.0.2.1:8090/topic" {
|
||||
t.Fatal(urls)
|
||||
}
|
||||
if localEndpoint(&url.URL{Host: "remote.example:8090", Scheme: "http"}, "test", addresses) {
|
||||
t.Fatal("remote endpoint guessed local")
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
// Handler serves the persistent connection. Canceling ctx stops active clients.
|
||||
func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
|
||||
started := time.Now()
|
||||
mux := http.NewServeMux()
|
||||
var runs *runner
|
||||
var runErr error
|
||||
@@ -66,7 +67,10 @@ func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
|
||||
if request.Type == protocol.List || request.Type == protocol.Submit {
|
||||
response.NotificationEndpoints = notificationEndpoints()
|
||||
}
|
||||
if request.Type == protocol.Ping {
|
||||
if request.Type == protocol.GetStatus {
|
||||
response.Type = protocol.Status
|
||||
response.Status = systemStatus(r, started, runErr)
|
||||
} else if request.Type == protocol.Ping {
|
||||
response.Time = time.Now().UTC().Format(time.RFC3339)
|
||||
} else if request.Type == protocol.ListTemplates {
|
||||
response.Type = protocol.Templates
|
||||
@@ -133,6 +137,9 @@ func Handler(ctx context.Context, stores ...*pipeline.Store) http.Handler {
|
||||
case protocol.ListRuns:
|
||||
response.Type = protocol.Runs
|
||||
response.Runs, err = runs.listRuns()
|
||||
if err == nil {
|
||||
response.Usage, err = stores[0].UsageStats(ctx)
|
||||
}
|
||||
case protocol.GetRun:
|
||||
response.Type = protocol.Run
|
||||
response.RunDetail, err = runs.getRun(request.RunID)
|
||||
|
||||
Reference in New Issue
Block a user