Skip to content
Draft
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
10 changes: 9 additions & 1 deletion discovery/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/url"
"os"
"os/signal"
"slices"
"sync"
"syscall"
"time"
Expand Down Expand Up @@ -54,9 +55,16 @@ func Root(out, errOut io.Writer) *cobra.Command {
return boa.NewUserInputError(err)
}
defer app.Close()
nodes := slices.Clone(p.Nodes)
for i, node := range nodes {
if node.Value.RawQuery != "" {
nodes[i].Value = node.Value.Clone()
nodes[i].Value.RawQuery = "REDACTED"
}
}
return toml.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{
"Network": &p.Network, "Listen": &p.Listen, "MetricsListen": &p.MetricsListen,
"Nodes": &p.Nodes, "Grants": &p.Grants,
"Nodes": &nodes, "Grants": &p.Grants,
"AdvertiseNodes": &p.AdvertiseNodes, "AdvertiseRunners": &p.AdvertiseRunners,
"RefreshInterval": &p.RefreshInterval, "MaxFailedRefreshes": &p.MaxFailedRefreshes,
})
Expand Down
43 changes: 32 additions & 11 deletions discovery/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ func TestDiscoveryConfigDefaultsAndPrecedence(t *testing.T) {
t.Setenv("HOME", t.TempDir())
out, err := execute(t, "--config=", "--print-config")
require.NoError(t, err)
require.NotContains(t, out, "\nNodes =")
for _, value := range []string{`Listen = "127.0.0.1:8939"`, `MetricsListen = "127.0.0.1:8940"`, `AdvertiseNodes = true`, `AdvertiseRunners = true`, `MaxFailedRefreshes = 6`, `RefreshInterval = "5m0s"`} {
require.Contains(t, out, value)
}
Expand All @@ -111,6 +112,9 @@ func TestDiscoveryConfigDefaultsAndPrecedence(t *testing.T) {
require.NoError(t, err)
require.Contains(t, out, `Listen = "unsafe@[::]:8939"`)
require.Contains(t, out, `MetricsListen = "unsafe@0.0.0.0:8940"`)
out, err = execute(t, "--nodes=", "--print-config")
require.NoError(t, err)
require.Contains(t, out, "\nNodes = []")
}

func TestDiscoveryInvalidConfig(t *testing.T) {
Expand All @@ -119,7 +123,8 @@ func TestDiscoveryInvalidConfig(t *testing.T) {
{"--metrics-listen="}, {"--metrics-listen=0.0.0.0:8940"},
{"--listen="}, {"--listen=[::]:8939"},
{"--nodes=ftp://child.example"}, {"--nodes=https://user:secret@child.example"},
{"--nodes=https://child.example?token=secret"}, {"--nodes=https://child.example#fragment"}, {"--runner-config=unused"},
{"--nodes=https://child.example?"}, {"--nodes=https://child.example?x=1#fragment"}, {"--runner-config=unused"},
{"--nodes=https://child.example?region=west coast"},
} {
for _, mode := range []string{"--print-config", "--dump"} {
out, err := execute(t, append(args, "--config=", mode)...)
Expand Down Expand Up @@ -216,28 +221,44 @@ func TestDiscoveryDumpResults(t *testing.T) {

func TestDiscoveryDumpConfiguration(t *testing.T) {
t.Setenv("HOME", t.TempDir())
paths := make(chan string, 3)
const query = "?orchestrator=0x1111111111111111111111111111111111111111&tag=a%2Fb&tag=c%20d"
const fileEndpoint = "/file%2Fdeploy/%64iscovery"
requests := make(chan string, 3)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths <- r.URL.Path
requests <- r.RequestURI
_, _ = io.WriteString(w, "[]")
}))
defer upstream.Close()
config := filepath.Join(t.TempDir(), "discovery.toml")
require.NoError(t, os.WriteFile(config, fmt.Appendf(nil, "Nodes = [%q]\nGrants = [%q]\nAdvertiseNodes = false\n", upstream.URL+"/file", strings.TrimPrefix(upstream.URL, "http://")), 0600))
for _, source := range []string{"file", "env", "cli"} {
if source == "env" {
require.NoError(t, os.WriteFile(config, fmt.Appendf(nil, "Nodes = [%q]\nGrants = [%q]\n", upstream.URL+fileEndpoint+query, strings.TrimPrefix(upstream.URL, "http://")), 0600))
printed, err := execute(t, "--print-config", "--config", config)
require.NoError(t, err)
require.Contains(t, printed, upstream.URL+fileEndpoint+"?REDACTED")
require.NotContains(t, printed, "orchestrator=")
schema := discoverySchema(t)
for _, tc := range []struct{ source, request, advertised string }{
{"file", fileEndpoint + query, "/file%2Fdeploy"},
{"env", "/env/discovery", "/env"},
{"cli", "/cli/catalog/" + query, "/cli/catalog/"},
} {
if tc.source == "env" {
t.Setenv("LIVEPEER_DISCOVERY_NODES", upstream.URL+"/env")
}
args := []string{"--dump", "--config", config}
if source == "cli" {
args = append(args, "--nodes", upstream.URL+"/cli")
if tc.source == "cli" {
args = append(args, "--nodes", upstream.URL+tc.request)
}
out, err := execute(t, args...)
require.NoError(t, err)
require.Equal(t, "[]\n", out)
require.NoError(t, validateDiscoveryJSON(t, schema, []byte(out)))
var entries []struct{ Nodes []discoveryNode }
require.NoError(t, json.Unmarshal([]byte(out), &entries))
require.Len(t, entries, 1)
require.Len(t, entries[0].Nodes, 1)
require.Equal(t, upstream.URL+tc.advertised, entries[0].Nodes[0].URL)
select {
case path := <-paths:
require.Equal(t, "/"+source+"/discovery", path)
case request := <-requests:
require.Equal(t, tc.request, request)
default:
t.Fatal("configured source was not queried")
}
Expand Down
56 changes: 21 additions & 35 deletions discovery/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,30 +27,12 @@ type Server struct {
metrics *observability.Metrics
logger *slog.Logger
mux *http.ServeMux
urls []*url.URL
hasSources bool
interval time.Duration
advertiseNodes, advertiseRunners bool
collector *discovery.Collector[discoveryRunner]
}

func discoveryBases(p Params) ([]*url.URL, error) {
urls := make([]*url.URL, 0, len(p.Nodes))
seen := map[string]bool{}
for _, item := range p.Nodes {
if err := discovery.ValidateURL(item.Value); err != nil {
return nil, err
}
u := item.Value.Clone()
u.RawPath = strings.TrimRight(u.EscapedPath(), "/")
u.Path, _ = url.PathUnescape(u.RawPath)
if !seen[u.String()] {
seen[u.String()] = true
urls = append(urls, u)
}
}
return urls, nil
}

// NewServer configures an inventory collector without runner or payment dependencies.
func NewServer(p Params, logger *slog.Logger) (*Server, error) {
if !p.Listen.IsValid() || !p.MetricsListen.IsValid() {
Expand All @@ -62,9 +44,13 @@ func NewServer(p Params, logger *slog.Logger) (*Server, error) {
if p.MaxFailedRefreshes < 0 {
return nil, errors.New("--max-failed-refreshes must be nonnegative")
}
urls, err := discoveryBases(p)
if err != nil {
return nil, err
endpoints := make([]*url.URL, 0, len(p.Nodes))
for _, node := range p.Nodes {
endpoint, err := discovery.StaticEndpoint(node.Value)
if err != nil {
return nil, err
}
endpoints = append(endpoints, endpoint)
}
policy, err := destination.New("discovery", p.Grants)
if err != nil {
Expand All @@ -75,18 +61,9 @@ func NewServer(p Params, logger *slog.Logger) (*Server, error) {
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
metrics := observability.New("discovery")
s := &Server{metrics: metrics, logger: logger.With("component", "discovery"), mux: http.NewServeMux(),
urls: urls, interval: p.RefreshInterval,
hasSources: len(endpoints) > 0, interval: p.RefreshInterval,
advertiseNodes: p.AdvertiseNodes, advertiseRunners: p.AdvertiseRunners,
collector: &discovery.Collector[discoveryRunner]{Client: client, MaxFailures: max(1, p.MaxFailedRefreshes), Logger: logger.With("component", "discovery"), Observe: metrics.Discovery}}
endpoints := make([]*url.URL, 0, len(urls))
for _, base := range urls {
endpoint := base.Clone()
endpoint.Path += "/discovery"
if endpoint.RawPath != "" {
endpoint.RawPath += "/discovery"
}
endpoints = append(endpoints, endpoint)
}
s.collector.SetSources(endpoints)
s.mux.HandleFunc("GET /discovery", s.discovery)
metrics.Snapshot(s.collector.CollectMetrics)
Expand Down Expand Up @@ -129,7 +106,7 @@ func (s *Server) discoveryBody(ctx context.Context) ([]byte, error) {
// dump collects one complete inventory on a fresh server, then closes it.
func (s *Server) dump(ctx context.Context, out io.Writer) error {
defer s.Close()
collect := len(s.urls) > 0 && (s.advertiseNodes || s.advertiseRunners)
collect := s.hasSources && (s.advertiseNodes || s.advertiseRunners)
if collect {
s.collector.Refresh(ctx, false)
}
Expand Down Expand Up @@ -159,7 +136,7 @@ func (s *Server) dump(ctx context.Context, out io.Writer) error {
// Run refreshes immediately and periodically until ctx ends. Run it once and
// wait for it to return before closing the server.
func (d *Server) Run(ctx context.Context) {
if (!d.advertiseNodes && !d.advertiseRunners) || len(d.urls) == 0 {
if (!d.advertiseNodes && !d.advertiseRunners) || !d.hasSources {
return
}
d.collector.Run(ctx, d.interval)
Expand All @@ -170,7 +147,16 @@ func (s *Server) discoveryResponse() []map[string]any {
entries := []discoveryEntry{}
for _, snapshot := range s.collector.Snapshots() {
if s.advertiseNodes {
nodes = append(nodes, discoveryNode{URL: strings.TrimSuffix(snapshot.URL, "/discovery"), QueriedAt: snapshot.QueriedAt})
u, _ := url.Parse(snapshot.URL) // A successful snapshot came from a parsed HTTP request.
u.RawQuery = ""
path := u.EscapedPath()
lastSlash := strings.LastIndexByte(path, '/')
lastSegment, _ := url.PathUnescape(path[lastSlash+1:])
if lastSlash >= 0 && lastSegment == "discovery" {
u.RawPath = path[:lastSlash]
u.Path, _ = url.PathUnescape(u.RawPath)
}
nodes = append(nodes, discoveryNode{URL: u.String(), QueriedAt: snapshot.QueriedAt})
}
if s.advertiseRunners {
entries = append(entries, snapshot.Entries...)
Expand Down
21 changes: 16 additions & 5 deletions discovery/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,22 @@ func TestDiscoveryBoundedConcurrencyAndPartialResults(t *testing.T) {
}

func TestDiscoverySources(t *testing.T) {
s := discoveryTestServer(t, "https://child.example/", "https://child.example")
require.Len(t, s.urls, 1)
encoded := discoveryTestServer(t, "https://child.example/deploy%2F/", "https://child.example/deploy%2F")
require.Len(t, encoded.urls, 1)
require.Equal(t, "https://child.example/deploy%2F", encoded.urls[0].String())
const base = "https://child.example"
const catalog = base + "/catalog?orchestrator="
sources := []string{base, base + "/", base + "/deploy%2F/", base + "/deploy%2F", catalog + "a", catalog + "a", catalog + "b"}
s := discoveryTestServer(t, sources...)
requests := make(chan string, len(sources))
s.collector.Client.Transport = discoveryRoundTrip(func(r *http.Request) (*http.Response, error) {
requests <- r.URL.RequestURI()
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("[]"))}, nil
})
s.collector.Refresh(t.Context(), false)
close(requests)
var queried []string
for uri := range requests {
queried = append(queried, uri)
}
require.ElementsMatch(t, []string{"/discovery", "/deploy%2F/discovery", "/catalog?orchestrator=a", "/catalog?orchestrator=b"}, queried)
}

func TestDiscoveryFailureThreshold(t *testing.T) {
Expand Down
29 changes: 27 additions & 2 deletions discovery/shared/inventory.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,39 @@ type Entry[R Runner] struct {
Runners []R `json:"runners"`
}

// ValidateURL checks discovery base URLs, retaining deployment paths.
// ValidateURL checks the query-free base URLs carried in inventories.
func ValidateURL(u *url.URL) error {
if destination.ValidateURL(u) != nil || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
if ValidateEndpointURL(u) != nil || u.RawQuery != "" {
return errors.New("discovery URL must be absolute HTTP(S) without credentials, query or fragment")
}
return nil
}

// ValidateEndpointURL checks polling URLs, which may carry a fixed query.
func ValidateEndpointURL(u *url.URL) error {
if destination.ValidateURL(u) != nil || u.User != nil || u.Fragment != "" || u.ForceQuery && u.RawQuery == "" {
return errors.New("discovery URL must be absolute HTTP(S) without credentials, an empty query, or a fragment")
}
if strings.ContainsFunc(u.RawQuery, func(r rune) bool { return r <= ' ' || r == '\x7f' }) {
return errors.New("discovery URL query contains an unescaped space or control character")
}
return nil
}

// StaticEndpoint adds /discovery to a configured base URL and preserves complete
// endpoints identified by a nonempty query.
func StaticEndpoint(u *url.URL) (*url.URL, error) {
if err := ValidateEndpointURL(u); err != nil {
return nil, err
}
endpoint := u.Clone()
if endpoint.RawQuery == "" {
endpoint.RawPath = strings.TrimRight(endpoint.EscapedPath(), "/") + "/discovery"
endpoint.Path, _ = url.PathUnescape(endpoint.RawPath)
}
return endpoint, nil
}

func Read(body io.Reader) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(body, MaxBody+1))
if err != nil || len(data) > MaxBody {
Expand Down
14 changes: 14 additions & 0 deletions discovery/shared/inventory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,26 @@ package shared

import (
"fmt"
"net/url"
"strings"
"testing"
"time"

"github.com/stretchr/testify/require"
)

func TestStaticEndpointQuery(t *testing.T) {
configured := &url.URL{
Scheme: "https", Host: "catalog.example", Path: "/inventory", ForceQuery: true, RawQuery: "orchestrator=one",
}
endpoint, err := StaticEndpoint(configured)
require.NoError(t, err)
require.Equal(t, "https://catalog.example/inventory?orchestrator=one", endpoint.String())
configured.RawQuery += "\t"
_, err = StaticEndpoint(configured)
require.ErrorContains(t, err, "control character")
}

type record struct {
URL string `json:"url"`
App string `json:"app"`
Expand Down Expand Up @@ -42,6 +55,7 @@ func TestDecodeValidation(t *testing.T) {
{"missing timestamp", envelope(`{"url":"https://r.example","app":"test"}`), 0, true},
{"wrong timestamp type", envelope(`{"url":"https://r.example","app":"test","observed_at":123}`), 0, true},
{"bad address", strings.ReplaceAll(envelope(valid), "https://orch.example", "file:///bad"), 0, true},
{"address with query", strings.ReplaceAll(envelope(valid), "https://orch.example", "https://orch.example?orchestrator=test"), 0, true},
{"wrong runner list", `[{"address":"https://orch.example","runners":{}}]`, 0, true},
{"trailing JSON", envelope(valid) + `[]`, 0, true}, {"null", "null", 0, true},
{"before skew", envelope(candidate(now.Add(ClockSkew - time.Nanosecond).Format(time.RFC3339Nano))), 1, false},
Expand Down
19 changes: 14 additions & 5 deletions docs/discovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Discovery collects and caches runner inventories from orchestrators and other
discovery sources. It owns no runners and needs no runner or payment credentials.

Copy the [configuration example](../configs/discovery/config.example.toml), set
`Nodes` to your source base URLs, and run:
`Nodes` to your discovery base URLs, and run:

```sh
livepeer discovery --config /etc/livepeer/discovery.toml
Expand All @@ -22,10 +22,19 @@ partial output. `--dump` is CLI-only and conflicts with `--print-config`.

## Sources and cache

Each source is queried at `<base URL>/discovery`, retaining any deployment path.
Duplicate URLs are skipped. Private sources require
`Grants`, such as `127.0.0.1:8935` for a local orchestrator. Redirects and URLs in
returned node metadata are not followed.
Each entry in `Nodes` (`--nodes`) is normally a discovery base URL, queried at
`<base URL>/discovery` while retaining any deployment path. A configured URL
with a nonempty query, such as
`https://catalog.example/deployment/discovery?orchestrator=0x1111111111111111111111111111111111111111`,
is polled as a complete endpoint. The upstream service interprets the query.
A bare `?` is invalid. The signer's `Orchestrators` (`--orchestrators`) follows
the same rules. For literal commas in URLs, the flags accept CSV with quoting,
environment lists split on commas, and TOML arrays preserve literal commas.

Duplicate polling URLs are skipped. Standalone discovery's `--print-config`
replaces source queries with `REDACTED`. Private sources require `Grants`, such
as `127.0.0.1:8935` for a local orchestrator. Redirects and URLs in returned
node metadata are not followed.

Refreshes run at startup and every `RefreshInterval` (default `5m`), with at most
five concurrent requests, a three-second timeout, and a 3 MiB limit per response.
Expand Down
11 changes: 7 additions & 4 deletions docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,13 @@ metadata/GPU fields.
Known fields must use the documented casing and types. Discovery skips malformed
records, including duplicate keys and invalid Unicode.
Discovery preserves complete runner records. `nodes` lists successfully queried,
non-evicted sources, and `queried_at` records each source's last successful query
time. Empty node and runner lists are omitted. With neither to advertise, discovery
returns `[]`. See [discovery setup](discovery.md) for caching,
advertising switches, limits, and metrics.
non-evicted sources, with `queried_at` recording each source's last successful
query time. Each advertised `url` strips any query and an exact final
`/discovery` path segment (including percent-encoded spellings), while retaining
other paths and trailing slashes. Empty node and runner lists are omitted. With
neither to advertise, discovery returns `[]`. See
[discovery setup](discovery.md) for caching, advertising switches, limits, and
metrics.

`observed_at` is an RFC3339 timestamp, allowing fractional seconds. Orchestrators
stamp local runners at response time; discovery preserves that timestamp.
Expand Down
Loading
Loading