v2.31.0-dev18 7b9923f

client.go RawHistoryFolder

1// Package remote provides an HTTP client for connecting to remote Gordon instances.
2package remote
3
4import (
5	"bytes"
6	"context"
7	"crypto/tls"
8	"encoding/json"
9	"errors"
10	"fmt"
11	"io"
12	"net/http"
13	"net/url"
14	"os"
15	"strings"
16	"sync"
17	"time"
18
19	"github.com/golang-jwt/jwt/v5"
20
21	"github.com/bnema/gordon/internal/adapters/dto"
22	"github.com/bnema/gordon/internal/domain"
23)
24
25// Client is an HTTP client for the Gordon admin API.
26type Client struct {
27	baseURL     string
28	token       string
29	httpClient  *http.Client
30	insecureTLS bool
31
32	// Ephemeral admin token exchange fields.
33	mu           sync.Mutex // protects ephemeral and ephemeralExp
34	subject      string     // JWT subject extracted from long-lived token
35	ephemeral    string     // cached ephemeral admin token
36	ephemeralExp time.Time  // expiry of cached ephemeral token
37}
38
39var (
40	retryMaxAttempts = 4
41	retryBaseDelay   = 250 * time.Millisecond
42)
43
44const maxErrorBodySize int64 = 1024 // cap error response reads at 1 KB
45
46// ClientOption configures the Client.
47type ClientOption func(*Client)
48
49// NewClient creates a new remote Gordon client.
50func NewClient(baseURL string, opts ...ClientOption) *Client {
51	// Normalize base URL
52	baseURL = strings.TrimSuffix(baseURL, "/")
53
54	c := &Client{
55		baseURL: baseURL,
56		httpClient: &http.Client{
57			Timeout: 2 * time.Minute,
58		},
59	}
60
61	for _, opt := range opts {
62		opt(c)
63	}
64
65	c.applyTLSConfig()
66
67	return c
68}
69
70// WithToken sets the authentication token.
71// The token must be a valid JWT — the subject claim is extracted for
72// ephemeral token exchange. If parsing fails, requests will return
73// an error rather than sending the long-lived token directly.
74func WithToken(token string) ClientOption {
75	return func(c *Client) {
76		c.token = token
77		c.subject = extractJWTSubject(token)
78	}
79}
80
81// extractJWTSubject parses a JWT without verification and returns the
82// "sub" claim.  Returns "" if the token is not a valid JWT or has no sub.
83func extractJWTSubject(tokenStr string) string {
84	if tokenStr == "" {
85		return ""
86	}
87	parser := jwt.NewParser()
88	claims := jwt.MapClaims{}
89	// We only need the claims; signature verification happens server-side.
90	_, _, err := parser.ParseUnverified(tokenStr, claims)
91	if err != nil {
92		return ""
93	}
94	sub, _ := claims.GetSubject()
95	return sub
96}
97
98// WithHTTPClient sets a custom HTTP client.
99func WithHTTPClient(client *http.Client) ClientOption {
100	return func(c *Client) {
101		c.httpClient = client
102	}
103}
104
105// WithTimeout sets the HTTP client timeout.
106func WithTimeout(timeout time.Duration) ClientOption {
107	return func(c *Client) {
108		c.httpClient.Timeout = timeout
109	}
110}
111
112// WithInsecureTLS disables TLS certificate verification for remote admin API requests.
113func WithInsecureTLS(insecure bool) ClientOption {
114	return func(c *Client) {
115		c.insecureTLS = insecure
116	}
117}
118
119// ephemeralMargin is the safety margin before expiry at which
120// the cached ephemeral token is considered stale.
121const ephemeralMargin = 30 * time.Second
122
123// ephemeralValid reports whether the cached ephemeral token is still usable.
124func (c *Client) ephemeralValid() bool {
125	return c.ephemeral != "" && time.Now().Before(c.ephemeralExp.Add(-ephemeralMargin))
126}
127
128// exchangeToken exchanges the long-lived token for a short-lived ephemeral
129// admin token via /auth/token. Follows the same pattern as ExchangeRegistryToken.
130// The caller must hold c.mu.
131func (c *Client) exchangeToken(ctx context.Context) error {
132	url := c.baseURL + "/auth/token?scope=admin:*:*&service=gordon-registry"
133
134	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
135	if err != nil {
136		return fmt.Errorf("ephemeral token exchange: %w", err)
137	}
138
139	req.SetBasicAuth(c.subject, c.token)
140	req.Header.Set("Accept", "application/json")
141
142	resp, err := c.httpClient.Do(req)
143	if err != nil {
144		return fmt.Errorf("ephemeral token exchange: %w", err)
145	}
146	defer resp.Body.Close()
147
148	if resp.StatusCode >= 400 {
149		body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
150		var errResp struct {
151			Error string `json:"error"`
152		}
153		if err := json.Unmarshal(body, &errResp); err == nil && errResp.Error != "" {
154			return fmt.Errorf("ephemeral token exchange: %s: %s", resp.Status, errResp.Error)
155		}
156		return fmt.Errorf("ephemeral token exchange: %s: %s", resp.Status, string(body))
157	}
158
159	var result dto.TokenResponse
160	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
161		return fmt.Errorf("ephemeral token exchange: decode: %w", err)
162	}
163
164	token := result.Token
165	if token == "" {
166		token = result.AccessToken
167	}
168	if token == "" {
169		return fmt.Errorf("ephemeral token exchange returned empty token")
170	}
171
172	if result.ExpiresIn <= 0 {
173		return fmt.Errorf("ephemeral token exchange: invalid expires_in value: %d", result.ExpiresIn)
174	}
175
176	c.ephemeral = token
177	c.ephemeralExp = time.Now().Add(time.Duration(result.ExpiresIn) * time.Second)
178	return nil
179}
180
181// bearerToken returns the token to use in Authorization headers.
182// It exchanges the long-lived token for an ephemeral one via /auth/token.
183// If subject extraction failed, uses "unknown" — the server validates everything.
184func (c *Client) bearerToken(ctx context.Context) (string, error) {
185	if c.token == "" {
186		return "", nil
187	}
188	if c.subject == "" {
189		c.subject = "unknown"
190	}
191	c.mu.Lock()
192	defer c.mu.Unlock()
193	if !c.ephemeralValid() {
194		if err := c.exchangeToken(ctx); err != nil {
195			return "", err
196		}
197	}
198	return c.ephemeral, nil
199}
200
201func (c *Client) applyTLSConfig() {
202	if !c.insecureTLS {
203		return
204	}
205
206	fmt.Fprintf(os.Stderr, "WARNING: TLS certificate verification disabled for %s\n", c.baseURL)
207
208	var transport *http.Transport
209	switch t := c.httpClient.Transport.(type) {
210	case *http.Transport:
211		transport = t.Clone()
212	case nil:
213		transport = http.DefaultTransport.(*http.Transport).Clone()
214	default:
215		// Cannot apply InsecureSkipVerify to a non-*http.Transport.
216		// Log a warning and leave the transport intact rather than
217		// silently replacing it (which would drop caller-provided behavior).
218		fmt.Fprintf(os.Stderr, "WARNING: --insecure requires *http.Transport, got %T; TLS override not applied\n", t)
219		return
220	}
221
222	if transport.TLSClientConfig == nil {
223		transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12}
224	} else {
225		transport.TLSClientConfig.MinVersion = tls.VersionTLS12
226	}
227	//nolint:gosec // Explicit CLI opt-in via --insecure for self-signed/private cert deployments.
228	transport.TLSClientConfig.InsecureSkipVerify = true
229	c.httpClient.Transport = transport
230}
231
232// request performs an HTTP request to the admin API.
233func (c *Client) request(ctx context.Context, method, path string, body any) (*http.Response, error) {
234	// Marshal body once so it can be replayed on 401 retry.
235	var jsonBody []byte
236	if body != nil {
237		var err error
238		jsonBody, err = json.Marshal(body)
239		if err != nil {
240			return nil, fmt.Errorf("failed to marshal request body: %w", err)
241		}
242	}
243
244	resp, err := c.doRequest(ctx, method, path, jsonBody)
245	if err != nil {
246		return nil, err
247	}
248
249	// On 401: invalidate ephemeral, re-exchange, retry once.
250	if resp.StatusCode == http.StatusUnauthorized && c.subject != "" && c.ephemeral != "" {
251		// Drain and close the first response.
252		_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxErrorBodySize))
253		resp.Body.Close()
254
255		c.mu.Lock()
256		c.ephemeral = ""
257		c.ephemeralExp = time.Time{}
258		if exErr := c.exchangeToken(ctx); exErr != nil {
259			c.mu.Unlock()
260			return nil, fmt.Errorf("token re-exchange after 401: %w", exErr)
261		}
262		c.mu.Unlock()
263		return c.doRequest(ctx, method, path, jsonBody)
264	}
265
266	return resp, nil
267}
268
269// doRequest builds and executes a single HTTP request to the admin API.
270func (c *Client) doRequest(ctx context.Context, method, path string, jsonBody []byte) (*http.Response, error) {
271	reqURL := c.baseURL + "/admin" + path
272
273	var bodyReader io.Reader
274	if jsonBody != nil {
275		bodyReader = bytes.NewReader(jsonBody)
276	}
277
278	req, err := http.NewRequestWithContext(ctx, method, reqURL, bodyReader)
279	if err != nil {
280		return nil, fmt.Errorf("failed to create request: %w", err)
281	}
282
283	req.Header.Set("Content-Type", "application/json")
284	req.Header.Set("Accept", "application/json")
285
286	bearer, err := c.bearerToken(ctx)
287	if err != nil {
288		return nil, err
289	}
290	if bearer != "" {
291		req.Header.Set("Authorization", "Bearer "+bearer)
292	}
293
294	resp, err := c.httpClient.Do(req)
295	if err != nil {
296		return nil, err
297	}
298
299	return resp, nil
300}
301
302// parseResponse parses a JSON response into the given target.
303func parseResponse(resp *http.Response, target any) error {
304	defer resp.Body.Close()
305
306	if resp.StatusCode >= 400 {
307		body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
308		return parseErrorResponse(resp, body)
309	}
310
311	if target != nil {
312		if err := json.NewDecoder(resp.Body).Decode(target); err != nil {
313			return fmt.Errorf("failed to decode response: %w", err)
314		}
315	}
316
317	return nil
318}
319
320// HTTPError represents an HTTP error response with a status code.
321// Use errors.As to check for specific status codes in error handling.
322type HTTPError struct {
323	StatusCode int
324	Status     string
325	Body       string
326	Cause      string
327	Hint       string
328	Logs       []string
329	Structured bool
330}
331
332func (e *HTTPError) Error() string {
333	return e.Status + ": " + e.Body
334}
335
336func parseErrorResponse(resp *http.Response, body []byte) error {
337	msg := string(body)
338	structured := false
339	var errResp struct {
340		Error string   `json:"error"`
341		Cause string   `json:"cause"`
342		Hint  string   `json:"hint"`
343		Logs  []string `json:"logs"`
344	}
345	if err := json.Unmarshal(body, &errResp); err == nil {
346		structured = errResp.Cause != "" || errResp.Hint != "" || len(errResp.Logs) > 0
347		if errResp.Error != "" {
348			msg = errResp.Error
349		}
350	}
351	return &HTTPError{
352		StatusCode: resp.StatusCode,
353		Status:     resp.Status,
354		Body:       msg,
355		Cause:      errResp.Cause,
356		Hint:       errResp.Hint,
357		Logs:       errResp.Logs,
358		Structured: structured,
359	}
360}
361
362func isRetryableRequestError(err error) bool {
363	return !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded)
364}
365
366func isRetryableStatus(status int) bool {
367	// Only retry gateway errors; retrying 500 on non-idempotent POSTs
368	// (deploy, restart, reload) can cause duplicate state changes.
369	return status == 502 || status == 503 || status == 504
370}
371
372func retryDelay(attempt int) time.Duration {
373	if attempt <= 1 {
374		return retryBaseDelay
375	}
376	return retryBaseDelay * time.Duration(1<<(attempt-1))
377}
378
379// requestWithRetry performs an HTTP request and retries transient failures.
380// Retries occur on transport errors and gateway errors (502, 503, 504).
381func (c *Client) requestWithRetry(ctx context.Context, method, path string, body any) (*http.Response, error) {
382	var lastErr error
383
384	for attempt := 1; attempt <= retryMaxAttempts; attempt++ {
385		resp, err := c.request(ctx, method, path, body)
386		if err != nil {
387			lastErr = err
388			if attempt == retryMaxAttempts || !isRetryableRequestError(err) {
389				return nil, err
390			}
391		} else {
392			if !isRetryableStatus(resp.StatusCode) {
393				return resp, nil
394			}
395
396			respBody, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
397			_ = resp.Body.Close()
398			lastErr = parseErrorResponse(resp, respBody)
399			if attempt == retryMaxAttempts {
400				return nil, lastErr
401			}
402		}
403
404		delay := retryDelay(attempt)
405		timer := time.NewTimer(delay)
406		select {
407		case <-ctx.Done():
408			timer.Stop()
409			return nil, ctx.Err()
410		case <-timer.C:
411		}
412	}
413
414	if lastErr != nil {
415		return nil, lastErr
416	}
417	return nil, fmt.Errorf("request failed after retries")
418}
419
420// Routes API
421
422// Type aliases for API types using shared DTO package.
423type RouteInfo = dto.RouteInfo
424type Attachment = dto.Attachment
425
426// ListRoutes returns all configured routes.
427func (c *Client) ListRoutes(ctx context.Context) ([]domain.Route, error) {
428	resp, err := c.request(ctx, http.MethodGet, "/routes", nil)
429	if err != nil {
430		return nil, err
431	}
432
433	var result struct {
434		Routes []domain.Route `json:"routes"`
435	}
436	if err := parseResponse(resp, &result); err != nil {
437		return nil, err
438	}
439
440	return result.Routes, nil
441}
442
443// ListRoutesWithDetails returns routes with network and attachment info.
444func (c *Client) ListRoutesWithDetails(ctx context.Context) ([]RouteInfo, error) {
445	resp, err := c.request(ctx, http.MethodGet, "/routes?detailed=true", nil)
446	if err != nil {
447		return nil, err
448	}
449
450	var result struct {
451		Routes []RouteInfo `json:"routes"`
452	}
453	if err := parseResponse(resp, &result); err != nil {
454		return nil, err
455	}
456
457	return result.Routes, nil
458}
459
460// ListNetworks returns Gordon-managed networks.
461func (c *Client) ListNetworks(ctx context.Context) ([]*domain.NetworkInfo, error) {
462	resp, err := c.request(ctx, http.MethodGet, "/networks", nil)
463	if err != nil {
464		return nil, err
465	}
466
467	var result struct {
468		Networks []*domain.NetworkInfo `json:"networks"`
469	}
470	if err := parseResponse(resp, &result); err != nil {
471		return nil, err
472	}
473
474	return result.Networks, nil
475}
476
477// ListAttachments returns attachments for a domain.
478func (c *Client) ListAttachments(ctx context.Context, routeDomain string) ([]Attachment, error) {
479	if routeDomain == "" {
480		return nil, fmt.Errorf("domain is required")
481	}
482	path := "/routes/" + url.PathEscape(routeDomain) + "/attachments"
483	resp, err := c.request(ctx, http.MethodGet, path, nil)
484	if err != nil {
485		return nil, err
486	}
487
488	var result struct {
489		Attachments []Attachment `json:"attachments"`
490	}
491	if err := parseResponse(resp, &result); err != nil {
492		return nil, err
493	}
494
495	return result.Attachments, nil
496}
497
498// GetRoute returns a specific route by domain.
499func (c *Client) GetRoute(ctx context.Context, routeDomain string) (*domain.Route, error) {
500	resp, err := c.request(ctx, http.MethodGet, "/routes/"+url.PathEscape(routeDomain), nil)
501	if err != nil {
502		return nil, err
503	}
504
505	var route domain.Route
506	if err := parseResponse(resp, &route); err != nil {
507		return nil, err
508	}
509
510	return &route, nil
511}
512
513// FindRoutesByImage returns all routes associated with the given image name.
514func (c *Client) FindRoutesByImage(ctx context.Context, imageName string) ([]domain.Route, error) {
515	resp, err := c.request(ctx, http.MethodGet, "/routes/by-image/"+url.PathEscape(imageName), nil)
516	if err != nil {
517		return nil, err
518	}
519
520	var result struct {
521		Image  string         `json:"image"`
522		Routes []domain.Route `json:"routes"`
523	}
524	if err := parseResponse(resp, &result); err != nil {
525		return nil, err
526	}
527
528	return result.Routes, nil
529}
530
531// AddRoute adds a new route.
532func (c *Client) AddRoute(ctx context.Context, route domain.Route) error {
533	resp, err := c.request(ctx, http.MethodPost, "/routes", route)
534	if err != nil {
535		return err
536	}
537	return parseResponse(resp, nil)
538}
539
540// UpdateRoute updates an existing route.
541func (c *Client) UpdateRoute(ctx context.Context, route domain.Route) error {
542	resp, err := c.request(ctx, http.MethodPut, "/routes/"+url.PathEscape(route.Domain), route)
543	if err != nil {
544		return err
545	}
546	return parseResponse(resp, nil)
547}
548
549// RemoveRoute removes a route by domain.
550func (c *Client) RemoveRoute(ctx context.Context, routeDomain string) error {
551	_, err := c.RemoveRouteWithCleanup(ctx, routeDomain)
552	return err
553}
554
555// RemoveRouteWithCleanup removes a route and returns the server cleanup report.
556func (c *Client) RemoveRouteWithCleanup(ctx context.Context, routeDomain string) (*dto.RouteDeleteResponse, error) {
557	resp, err := c.request(ctx, http.MethodDelete, "/routes/"+url.PathEscape(routeDomain), nil)
558	if err != nil {
559		return nil, fmt.Errorf("delete route %s failed: %w", routeDomain, err)
560	}
561	var result dto.RouteDeleteResponse
562	if err := parseResponse(resp, &result); err != nil {
563		return nil, fmt.Errorf("parse delete route %s response: %w", routeDomain, err)
564	}
565	return &result, nil
566}
567
568func (c *Client) Bootstrap(ctx context.Context, req dto.BootstrapRequest) (*dto.BootstrapResponse, error) {
569	resp, err := c.request(ctx, http.MethodPost, "/bootstrap", req)
570	if err != nil {
571		return nil, err
572	}
573	var result dto.BootstrapResponse
574	if err := parseResponse(resp, &result); err != nil {
575		return nil, err
576	}
577	return &result, nil
578}
579
580// Secrets API
581
582// AttachmentSecrets represents secrets for an attachment container.
583type AttachmentSecrets struct {
584	Service string   `json:"service"`
585	Keys    []string `json:"keys"`
586}
587
588// SecretsListResult contains domain secrets and any attachment secrets.
589type SecretsListResult struct {
590	Domain      string              `json:"domain"`
591	Keys        []string            `json:"keys"`
592	Attachments []AttachmentSecrets `json:"attachments,omitempty"`
593}
594
595// ListSecrets returns the list of secret keys for a domain.
596func (c *Client) ListSecrets(ctx context.Context, secretDomain string) ([]string, error) {
597	result, err := c.ListSecretsWithAttachments(ctx, secretDomain)
598	if err != nil {
599		return nil, err
600	}
601	return result.Keys, nil
602}
603
604// ListSecretsWithAttachments returns domain secrets and attachment secrets.
605func (c *Client) ListSecretsWithAttachments(ctx context.Context, secretDomain string) (*SecretsListResult, error) {
606	resp, err := c.request(ctx, http.MethodGet, "/secrets/"+url.PathEscape(secretDomain), nil)
607	if err != nil {
608		return nil, err
609	}
610
611	var result SecretsListResult
612	if err := parseResponse(resp, &result); err != nil {
613		return nil, err
614	}
615
616	return &result, nil
617}
618
619// SetSecrets sets secrets for a domain.
620func (c *Client) SetSecrets(ctx context.Context, secretDomain string, secrets map[string]string) error {
621	resp, err := c.request(ctx, http.MethodPost, "/secrets/"+url.PathEscape(secretDomain), secrets)
622	if err != nil {
623		return err
624	}
625	return parseResponse(resp, nil)
626}
627
628// DeleteSecret removes a secret from a domain.
629func (c *Client) DeleteSecret(ctx context.Context, secretDomain, key string) error {
630	resp, err := c.request(ctx, http.MethodDelete, "/secrets/"+url.PathEscape(secretDomain)+"/"+url.PathEscape(key), nil)
631	if err != nil {
632		return err
633	}
634	return parseResponse(resp, nil)
635}
636
637// SetAttachmentSecrets sets secrets for an attachment container.
638func (c *Client) SetAttachmentSecrets(ctx context.Context, domain, service string, secrets map[string]string) error {
639	path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service)
640	resp, err := c.request(ctx, http.MethodPost, path, secrets)
641	if err != nil {
642		return err
643	}
644	return parseResponse(resp, nil)
645}
646
647// DeleteAttachmentSecret removes a secret from an attachment container.
648func (c *Client) DeleteAttachmentSecret(ctx context.Context, domain, service, key string) error {
649	path := "/secrets/" + url.PathEscape(domain) + "/attachments/" + url.PathEscape(service) + "/" + url.PathEscape(key)
650	resp, err := c.request(ctx, http.MethodDelete, path, nil)
651	if err != nil {
652		return err
653	}
654	return parseResponse(resp, nil)
655}
656
657// Status API
658
659// Status represents the Gordon server status.
660type Status struct {
661	Routes           int               `json:"routes"`
662	RegistryDomain   string            `json:"registry_domain"`
663	RegistryPort     int               `json:"registry_port"`
664	ServerPort       int               `json:"server_port"`
665	AutoRoute        bool              `json:"auto_route"`
666	NetworkIsolation bool              `json:"network_isolation"`
667	ContainerStatus  map[string]string `json:"container_status"`
668}
669
670// GetTLSStatus returns the public TLS/ACME status.
671func (c *Client) GetTLSStatus(ctx context.Context) (*dto.TLSStatusResponse, error) {
672	resp, err := c.request(ctx, http.MethodGet, "/tls/status", nil)
673	if err != nil {
674		return nil, err
675	}
676
677	var status dto.TLSStatusResponse
678	if err := parseResponse(resp, &status); err != nil {
679		return nil, err
680	}
681
682	return &status, nil
683}
684
685// GetStatus returns the Gordon server status.
686func (c *Client) GetStatus(ctx context.Context) (*Status, error) {
687	resp, err := c.request(ctx, http.MethodGet, "/status", nil)
688	if err != nil {
689		return nil, err
690	}
691
692	var status Status
693	if err := parseResponse(resp, &status); err != nil {
694		return nil, err
695	}
696
697	return &status, nil
698}
699
700// RouteHealth represents the health status of a route.
701type RouteHealth struct {
702	ContainerStatus string `json:"container_status"`
703	HTTPStatus      int    `json:"http_status"`
704	ResponseTimeMs  int64  `json:"response_time_ms"`
705	Healthy         bool   `json:"healthy"`
706	Error           string `json:"error"`
707}
708
709// Backups API
710
711// Images API
712
713// ListImages returns runtime images and registry tags from the admin API.
714func (c *Client) ListImages(ctx context.Context) ([]dto.Image, error) {
715	resp, err := c.request(ctx, http.MethodGet, "/images", nil)
716	if err != nil {
717		return nil, err
718	}
719
720	var result dto.ImagesResponse
721	if err := parseResponse(resp, &result); err != nil {
722		return nil, err
723	}
724
725	return result.Images, nil
726}
727
728// PruneImages prunes runtime and registry images.
729func (c *Client) PruneImages(ctx context.Context, req dto.ImagePruneRequest) (*dto.ImagePruneResponse, error) {
730	if req.KeepLast != nil && *req.KeepLast < 0 {
731		return nil, fmt.Errorf("keep_last must be >= 0")
732	}
733
734	resp, err := c.request(ctx, http.MethodPost, "/images/prune", req)
735	if err != nil {
736		return nil, err
737	}
738
739	var result dto.ImagePruneResponse
740	if err := parseResponse(resp, &result); err != nil {
741		return nil, err
742	}
743
744	return &result, nil
745}
746
747// ListBackups returns backups globally or for a domain.
748func (c *Client) ListBackups(ctx context.Context, backupDomain string) ([]dto.BackupJob, error) {
749	path := "/backups"
750	if backupDomain != "" {
751		path += "/" + url.PathEscape(backupDomain)
752	}
753
754	resp, err := c.request(ctx, http.MethodGet, path, nil)
755	if err != nil {
756		return nil, err
757	}
758
759	var result dto.BackupsResponse
760	if err := parseResponse(resp, &result); err != nil {
761		return nil, err
762	}
763
764	return result.Backups, nil
765}
766
767// BackupStatus returns aggregate backup status.
768func (c *Client) BackupStatus(ctx context.Context) ([]dto.BackupJob, error) {
769	resp, err := c.request(ctx, http.MethodGet, "/backups/status", nil)
770	if err != nil {
771		return nil, err
772	}
773
774	var result dto.BackupsResponse
775	if err := parseResponse(resp, &result); err != nil {
776		return nil, err
777	}
778
779	return result.Backups, nil
780}
781
782// RunBackup triggers a backup for a domain.
783func (c *Client) RunBackup(ctx context.Context, backupDomain, dbName string) (*dto.BackupRunResponse, error) {
784	if backupDomain == "" {
785		return nil, fmt.Errorf("domain cannot be empty")
786	}
787
788	resp, err := c.request(ctx, http.MethodPost, "/backups/"+url.PathEscape(backupDomain), dto.BackupRunRequest{DB: dbName})
789	if err != nil {
790		return nil, err
791	}
792
793	var result dto.BackupRunResponse
794	if err := parseResponse(resp, &result); err != nil {
795		return nil, err
796	}
797
798	return &result, nil
799}
800
801// DetectDatabases detects supported databases for a domain.
802func (c *Client) DetectDatabases(ctx context.Context, backupDomain string) ([]dto.DatabaseInfo, error) {
803	if backupDomain == "" {
804		return nil, fmt.Errorf("domain cannot be empty")
805	}
806
807	resp, err := c.request(ctx, http.MethodGet, "/backups/"+url.PathEscape(backupDomain)+"/detect", nil)
808	if err != nil {
809		return nil, err
810	}
811
812	var result dto.BackupDetectResponse
813	if err := parseResponse(resp, &result); err != nil {
814		return nil, err
815	}
816
817	return result.Databases, nil
818}
819
820// GetHealth returns health status for all routes with HTTP probing.
821func (c *Client) GetHealth(ctx context.Context) (map[string]*RouteHealth, error) {
822	resp, err := c.request(ctx, http.MethodGet, "/health", nil)
823	if err != nil {
824		return nil, err
825	}
826
827	var result struct {
828		Health map[string]*RouteHealth `json:"health"`
829	}
830	if err := parseResponse(resp, &result); err != nil {
831		return nil, err
832	}
833
834	return result.Health, nil
835}
836
837// Reload triggers a configuration reload.
838func (c *Client) Reload(ctx context.Context) error {
839	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/reload", nil)
840	if err != nil {
841		return err
842	}
843	return parseResponse(resp, nil)
844}
845
846// Config API
847
848// Config represents the Gordon configuration.
849type Config struct {
850	Server struct {
851		Port           int    `json:"port"`
852		RegistryPort   int    `json:"registry_port"`
853		RegistryDomain string `json:"registry_domain"`
854		DataDir        string `json:"data_dir,omitempty"`
855	} `json:"server"`
856	AutoRoute struct {
857		Enabled bool `json:"enabled"`
858	} `json:"auto_route"`
859	NetworkIsolation struct {
860		Enabled bool   `json:"enabled"`
861		Prefix  string `json:"prefix"`
862	} `json:"network_isolation"`
863	Routes         []domain.Route  `json:"routes"`
864	ExternalRoutes []ExternalRoute `json:"external_routes"`
865}
866
867// ExternalRoute represents a redacted external route config entry.
868type ExternalRoute struct {
869	Domain string `json:"domain"`
870	Target string `json:"target,omitempty"`
871}
872
873// GetConfig returns the Gordon configuration.
874func (c *Client) GetConfig(ctx context.Context) (*Config, error) {
875	resp, err := c.request(ctx, http.MethodGet, "/config", nil)
876	if err != nil {
877		return nil, err
878	}
879
880	var config Config
881	if err := parseResponse(resp, &config); err != nil {
882		return nil, err
883	}
884
885	return &config, nil
886}
887
888// Ping checks if the remote Gordon instance is reachable.
889func (c *Client) Ping(ctx context.Context) error {
890	_, err := c.GetStatus(ctx)
891	return err
892}
893
894// Deploy API
895
896// DeployResult contains the result of a deployment.
897type DeployResult struct {
898	Status      string `json:"status"`
899	ContainerID string `json:"container_id"`
900	Domain      string `json:"domain"`
901}
902
903// Deploy triggers a deployment for the specified domain.
904func (c *Client) Deploy(ctx context.Context, deployDomain string) (*DeployResult, error) {
905	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy/"+url.PathEscape(deployDomain), nil)
906	if err != nil {
907		return nil, err
908	}
909
910	var result DeployResult
911	if err := parseResponse(resp, &result); err != nil {
912		return nil, err
913	}
914
915	return &result, nil
916}
917
918// DeployIntent tells the server that a CLI-managed push is about to happen,
919// suppressing event-based deploys for this image.
920func (c *Client) DeployIntent(ctx context.Context, imageName string) error {
921	imageName = strings.TrimSpace(imageName)
922	if imageName == "" {
923		return fmt.Errorf("image name cannot be empty")
924	}
925	resp, err := c.requestWithRetry(ctx, http.MethodPost, "/deploy-intent/"+url.PathEscape(imageName), nil)
926	if err != nil {
927		return err
928	}
929	return parseResponse(resp, nil)
930}
931
932// Restart API
933
934// RestartResult contains the result of a restart.
935type RestartResult struct {
936	Status string `json:"status"`
937	Domain string `json:"domain"`
938}
939
940// Restart triggers a container restart for the specified domain.
941func (c *Client) Restart(ctx context.Context, restartDomain string, withAttachments bool) (*RestartResult, error) {
942	if restartDomain == "" {
943		return nil, fmt.Errorf("domain cannot be empty")
944	}
945	path := "/restart/" + url.PathEscape(restartDomain)
946	if withAttachments {
947		path += "?attachments=true"
948	}
949	resp, err := c.requestWithRetry(ctx, http.MethodPost, path, nil)
950	if err != nil {
951		return nil, err
952	}
953
954	var result RestartResult
955	if err := parseResponse(resp, &result); err != nil {
956		return nil, err
957	}
958
959	return &result, nil
960}
961
962// Tags API
963
964// ListTags returns available tags for a repository.
965func (c *Client) ListTags(ctx context.Context, repository string) ([]string, error) {
966	if repository == "" {
967		return nil, fmt.Errorf("repository cannot be empty")
968	}
969	resp, err := c.request(ctx, http.MethodGet, "/tags/"+url.PathEscape(repository), nil)
970	if err != nil {
971		return nil, err
972	}
973	var result struct {
974		Repository string   `json:"repository"`
975		Tags       []string `json:"tags"`
976	}
977	if err := parseResponse(resp, &result); err != nil {
978		return nil, err
979	}
980	return result.Tags, nil
981}
982
983// Logs API
984
985// GetProcessLogs returns Gordon process logs.
986func (c *Client) GetProcessLogs(ctx context.Context, lines int) ([]string, error) {
987	path := fmt.Sprintf("/logs?lines=%d", lines)
988	resp, err := c.request(ctx, http.MethodGet, path, nil)
989	if err != nil {
990		return nil, err
991	}
992
993	var result struct {
994		Lines []string `json:"lines"`
995	}
996	if err := parseResponse(resp, &result); err != nil {
997		return nil, err
998	}
999
1000	return result.Lines, nil
1001}
1002
1003// GetContainerLogs returns container logs for a specific domain.
1004func (c *Client) GetContainerLogs(ctx context.Context, logDomain string, lines int) ([]string, error) {
1005	path := fmt.Sprintf("/logs/%s?lines=%d", url.PathEscape(logDomain), lines)
1006	resp, err := c.request(ctx, http.MethodGet, path, nil)
1007	if err != nil {
1008		return nil, err
1009	}
1010
1011	var result struct {
1012		Domain string   `json:"domain"`
1013		Lines  []string `json:"lines"`
1014	}
1015	if err := parseResponse(resp, &result); err != nil {
1016		return nil, err
1017	}
1018
1019	return result.Lines, nil
1020}
1021
1022// StreamProcessLogs returns a channel that streams Gordon process log lines via SSE.
1023// The caller is responsible for reading from the channel until it's closed.
1024func (c *Client) StreamProcessLogs(ctx context.Context, lines int) (<-chan string, error) {
1025	path := fmt.Sprintf("/logs?lines=%d&follow=true", lines)
1026	return c.streamLogs(ctx, path)
1027}
1028
1029// StreamContainerLogs returns a channel that streams container log lines via SSE.
1030// The caller is responsible for reading from the channel until it's closed.
1031func (c *Client) StreamContainerLogs(ctx context.Context, logDomain string, lines int) (<-chan string, error) {
1032	path := fmt.Sprintf("/logs/%s?lines=%d&follow=true", url.PathEscape(logDomain), lines)
1033	return c.streamLogs(ctx, path)
1034}
1035
1036// Attachments Config API
1037
1038// ListOrphanedAttachments returns running attachment containers no longer configured.
1039func (c *Client) ListOrphanedAttachments(ctx context.Context) ([]domain.CleanupAttachment, error) {
1040	resp, err := c.request(ctx, http.MethodGet, "/attachments/orphans", nil)
1041	if err != nil {
1042		return nil, err
1043	}
1044	var result struct {
1045		Attachments []domain.CleanupAttachment `json:"attachments"`
1046	}
1047	if err := parseResponse(resp, &result); err != nil {
1048		return nil, err
1049	}
1050	return result.Attachments, nil
1051}
1052
1053// CleanupOrphanedAttachments optionally stops/removes orphaned attachment containers.
1054func (c *Client) CleanupOrphanedAttachments(ctx context.Context, owner string, stop bool) (*domain.CleanupReport, error) {
1055	path := "/attachments/prune"
1056	params := url.Values{}
1057	if stop {
1058		params.Set("stop", "true")
1059	}
1060	if owner != "" {
1061		params.Set("owner", owner)
1062	}
1063	if encoded := params.Encode(); encoded != "" {
1064		path += "?" + encoded
1065	}
1066	resp, err := c.request(ctx, http.MethodPost, path, nil)
1067	if err != nil {
1068		return nil, fmt.Errorf("cleanup orphaned attachments failed: %w", err)
1069	}
1070	var result domain.CleanupReport
1071	if err := parseResponse(resp, &result); err != nil {
1072		return nil, fmt.Errorf("parse orphaned attachment cleanup response: %w", err)
1073	}
1074	return &result, nil
1075}
1076
1077// GetAllAttachmentsConfig returns all configured attachments.
1078func (c *Client) GetAllAttachmentsConfig(ctx context.Context) (map[string][]string, error) {
1079	resp, err := c.request(ctx, http.MethodGet, "/attachments", nil)
1080	if err != nil {
1081		return nil, err
1082	}
1083
1084	var result struct {
1085		Attachments map[string][]string `json:"attachments"`
1086	}
1087	if err := parseResponse(resp, &result); err != nil {
1088		return nil, err
1089	}
1090
1091	return result.Attachments, nil
1092}
1093
1094// GetAttachmentsConfig returns attachments for a specific domain/group from config.
1095func (c *Client) GetAttachmentsConfig(ctx context.Context, domainOrGroup string) ([]string, error) {
1096	if domainOrGroup == "" {
1097		return nil, fmt.Errorf("domain or group is required")
1098	}
1099	path := "/attachments/" + url.PathEscape(domainOrGroup)
1100	resp, err := c.request(ctx, http.MethodGet, path, nil)
1101	if err != nil {
1102		return nil, err
1103	}
1104
1105	var result struct {
1106		Target string   `json:"target"`
1107		Images []string `json:"images"`
1108	}
1109	if err := parseResponse(resp, &result); err != nil {
1110		return nil, err
1111	}
1112
1113	return result.Images, nil
1114}
1115
1116// FindAttachmentTargetsByImage returns all attachment targets associated with the given image name.
1117func (c *Client) FindAttachmentTargetsByImage(ctx context.Context, imageName string) ([]string, error) {
1118	resp, err := c.request(ctx, http.MethodGet, "/attachments/by-image/"+url.PathEscape(imageName), nil)
1119	if err != nil {
1120		return nil, err
1121	}
1122
1123	var result dto.AttachmentTargetsByImageResponse
1124	if err := parseResponse(resp, &result); err != nil {
1125		return nil, err
1126	}
1127
1128	return result.Targets, nil
1129}
1130
1131// AddAttachment adds an attachment to a domain/group.
1132func (c *Client) AddAttachment(ctx context.Context, domainOrGroup, image string) error {
1133	if domainOrGroup == "" {
1134		return fmt.Errorf("domain or group is required")
1135	}
1136	if image == "" {
1137		return fmt.Errorf("image is required")
1138	}
1139	path := "/attachments/" + url.PathEscape(domainOrGroup)
1140	resp, err := c.request(ctx, http.MethodPost, path, struct {
1141		Image string `json:"image"`
1142	}{Image: image})
1143	if err != nil {
1144		return err
1145	}
1146	return parseResponse(resp, nil)
1147}
1148
1149// RemoveAttachment removes an attachment from a domain/group.
1150func (c *Client) RemoveAttachment(ctx context.Context, domainOrGroup, image string) error {
1151	if domainOrGroup == "" {
1152		return fmt.Errorf("domain or group is required")
1153	}
1154	if image == "" {
1155		return fmt.Errorf("image is required")
1156	}
1157	path := "/attachments/" + url.PathEscape(domainOrGroup) + "/" + url.PathEscape(image)
1158	resp, err := c.request(ctx, http.MethodDelete, path, nil)
1159	if err != nil {
1160		return err
1161	}
1162	return parseResponse(resp, nil)
1163}
1164
1165func (c *Client) GetAutoRouteAllowedDomains(ctx context.Context) ([]string, error) {
1166	resp, err := c.request(ctx, http.MethodGet, "/autoroute/allowed-domains", nil)
1167	if err != nil {
1168		return nil, err
1169	}
1170
1171	var result dto.AutoRouteAllowedDomainsResponse
1172	if err := parseResponse(resp, &result); err != nil {
1173		return nil, err
1174	}
1175
1176	return result.Domains, nil
1177}
1178
1179func (c *Client) AddAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1180	if strings.TrimSpace(pattern) == "" {
1181		return fmt.Errorf("pattern must not be empty")
1182	}
1183	resp, err := c.request(ctx, http.MethodPost, "/autoroute/allowed-domains", dto.AutoRouteAllowedDomainRequest{Pattern: pattern})
1184	if err != nil {
1185		return err
1186	}
1187	return parseResponse(resp, nil)
1188}
1189
1190func (c *Client) RemoveAutoRouteAllowedDomain(ctx context.Context, pattern string) error {
1191	if strings.TrimSpace(pattern) == "" {
1192		return fmt.Errorf("pattern must not be empty")
1193	}
1194	resp, err := c.request(ctx, http.MethodDelete, "/autoroute/allowed-domains/"+url.PathEscape(pattern), nil)
1195	if err != nil {
1196		return err
1197	}
1198	return parseResponse(resp, nil)
1199}
1200
1201// openSSEStream opens an SSE connection to the given admin path and returns the response.
1202func (c *Client) openSSEStream(ctx context.Context, path string) (*http.Response, error) {
1203	streamURL := c.baseURL + "/admin" + path
1204
1205	req, err := http.NewRequestWithContext(ctx, http.MethodGet, streamURL, nil)
1206	if err != nil {
1207		return nil, fmt.Errorf("failed to create request: %w", err)
1208	}
1209
1210	req.Header.Set("Accept", "text/event-stream")
1211	bearer, err := c.bearerToken(ctx)
1212	if err != nil {
1213		return nil, err
1214	}
1215	if bearer != "" {
1216		req.Header.Set("Authorization", "Bearer "+bearer)
1217	}
1218
1219	// Use the same transport as the main client (honoring TLS config and
1220	// custom transports) but without a timeout so streaming doesn't get cut off.
1221	streamClient := &http.Client{
1222		Transport: c.httpClient.Transport,
1223	}
1224	resp, err := streamClient.Do(req)
1225	if err != nil {
1226		return nil, fmt.Errorf("failed to connect: %w", err)
1227	}
1228
1229	if resp.StatusCode >= 400 {
1230		body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodySize))
1231		resp.Body.Close()
1232		return nil, fmt.Errorf("%s: %s", resp.Status, string(body))
1233	}
1234
1235	return resp, nil
1236}
1237
1238// streamLogs handles SSE streaming for log endpoints.
1239func (c *Client) streamLogs(ctx context.Context, path string) (<-chan string, error) {
1240	resp, err := c.openSSEStream(ctx, path)
1241	if err != nil {
1242		return nil, err
1243	}
1244
1245	ch := make(chan string, 100)
1246
1247	go func() {
1248		defer close(ch)
1249		defer resp.Body.Close()
1250
1251		buf := make([]byte, 4096)
1252		var lineBuffer strings.Builder
1253
1254		for {
1255			select {
1256			case <-ctx.Done():
1257				return
1258			default:
1259			}
1260
1261			n, err := resp.Body.Read(buf)
1262			if n > 0 {
1263				lineBuffer.Write(buf[:n])
1264			}
1265			if err != nil {
1266				return // EOF or context cancellation — clean exit
1267			}
1268
1269			// Process complete SSE events
1270			for {
1271				data := lineBuffer.String()
1272				idx := strings.Index(data, "\n\n")
1273				if idx == -1 {
1274					break
1275				}
1276
1277				event := data[:idx]
1278				lineBuffer.Reset()
1279				lineBuffer.WriteString(data[idx+2:])
1280
1281				// Parse SSE data lines
1282				for _, line := range strings.Split(event, "\n") {
1283					if strings.HasPrefix(line, "data: ") {
1284						logLine := strings.TrimPrefix(line, "data: ")
1285						select {
1286						case ch <- logLine:
1287						case <-ctx.Done():
1288							return
1289						}
1290					}
1291				}
1292			}
1293		}
1294	}()
1295
1296	return ch, nil
1297}
1298
1299// VerifyAuth checks if authentication session is valid.
1300func (c *Client) VerifyAuth(ctx context.Context) (*dto.AuthVerifyResponse, error) {
1301	resp, err := c.request(ctx, http.MethodGet, "/auth/verify", nil)
1302	if err != nil {
1303		return nil, err
1304	}
1305
1306	var result dto.AuthVerifyResponse
1307	if err := parseResponse(resp, &result); err != nil {
1308		return nil, err
1309	}
1310
1311	return &result, nil
1312}
1313
1314// ListVolumes lists all volumes via the admin API.
1315func (c *Client) ListVolumes(ctx context.Context) ([]dto.Volume, error) {
1316	resp, err := c.request(ctx, http.MethodGet, "/volumes", nil)
1317	if err != nil {
1318		return nil, err
1319	}
1320
1321	var volumes []dto.Volume
1322	if err := parseResponse(resp, &volumes); err != nil {
1323		return nil, err
1324	}
1325
1326	return volumes, nil
1327}
1328
1329// PruneVolumes prunes orphaned volumes via the admin API.
1330func (c *Client) PruneVolumes(ctx context.Context, req dto.VolumePruneRequest) (*dto.VolumePruneResponse, error) {
1331	resp, err := c.request(ctx, http.MethodPost, "/volumes/prune", req)
1332	if err != nil {
1333		return nil, err
1334	}
1335
1336	var result dto.VolumePruneResponse
1337	if err := parseResponse(resp, &result); err != nil {
1338		return nil, err
1339	}
1340
1341	return &result, nil
1342}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 7

Tags 106

↑↓ moveenter openesc close