Skip to content

Commit 4fbc0ff

Browse files
committed
fixup! feat: add endpoint to get listening ports in agent
1 parent 3f741c6 commit 4fbc0ff

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

codersdk/agentconn.go

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"context"
55
"encoding/binary"
66
"encoding/json"
7+
"fmt"
8+
"io"
79
"net"
810
"net/http"
911
"net/netip"
@@ -176,6 +178,19 @@ func (c *AgentConn) statisticsClient() *http.Client {
176178
// request, and this triggers goleak in tests
177179
DisableKeepAlives: true,
178180
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
181+
if network != "tcp" {
182+
return nil, xerrors.Errorf("network must be tcp")
183+
}
184+
host, port, err := net.SplitHostPort(addr)
185+
if err != nil {
186+
return nil, xerrors.Errorf("split host port %q: %w", addr, err)
187+
}
188+
// Verify that host is TailnetIP and port is
189+
// TailnetStatisticsPort.
190+
if host != TailnetIP.String() || port != strconv.Itoa(TailnetStatisticsPort) {
191+
return nil, xerrors.Errorf("request %q does not appear to be for statistics server", addr)
192+
}
193+
179194
conn, err := c.DialContextTCP(context.Background(), netip.AddrPortFrom(TailnetIP, uint16(TailnetStatisticsPort)))
180195
if err != nil {
181196
return nil, xerrors.Errorf("dial statistics: %w", err)
@@ -187,6 +202,18 @@ func (c *AgentConn) statisticsClient() *http.Client {
187202
}
188203
}
189204

205+
func (c *AgentConn) doStatisticsRequest(ctx context.Context, method, path string, body io.Reader) (*http.Response, error) {
206+
host := net.JoinHostPort(TailnetIP.String(), strconv.Itoa(TailnetStatisticsPort))
207+
url := fmt.Sprintf("http://%s%s", host, path)
208+
209+
req, err := http.NewRequestWithContext(ctx, method, url, body)
210+
if err != nil {
211+
return nil, xerrors.Errorf("new statistics server request to %q: %w", url, err)
212+
}
213+
214+
return c.statisticsClient().Do(req)
215+
}
216+
190217
type ListeningPortsResponse struct {
191218
// If there are no ports in the list, nothing should be displayed in the UI.
192219
// There must not be a "no ports available" message or anything similar, as
@@ -208,11 +235,7 @@ type ListeningPort struct {
208235
}
209236

210237
func (c *AgentConn) ListeningPorts(ctx context.Context) (ListeningPortsResponse, error) {
211-
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://agent-stats/api/v0/listening-ports", nil)
212-
if err != nil {
213-
return ListeningPortsResponse{}, xerrors.Errorf("new request: %w", err)
214-
}
215-
res, err := c.statisticsClient().Do(req)
238+
res, err := c.doStatisticsRequest(ctx, http.MethodGet, "/api/v0/listening-ports", nil)
216239
if err != nil {
217240
return ListeningPortsResponse{}, xerrors.Errorf("do request: %w", err)
218241
}

0 commit comments

Comments
 (0)