1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
package mountmanager
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"time"
)
// Client talks to the mount service over a Unix domain socket.
type Client struct {
httpClient *http.Client
baseURL string
}
// NewClient builds a new Client for the given endpoint.
func NewClient(endpoint string) (*Client, error) {
scheme, address, err := ParseEndpoint(endpoint)
if err != nil {
return nil, err
}
if scheme != "unix" {
return nil, fmt.Errorf("unsupported endpoint scheme: %s", scheme)
}
dialer := &net.Dialer{}
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, "unix", address)
},
}
return &Client{
httpClient: &http.Client{
Timeout: 30 * time.Second,
Transport: transport,
},
baseURL: "http://unix",
}, nil
}
// Mount mounts a volume using the mount service.
func (c *Client) Mount(req *MountRequest) (*MountResponse, error) {
var resp MountResponse
if err := c.doPost("/mount", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// Unmount unmounts a volume using the mount service.
func (c *Client) Unmount(req *UnmountRequest) (*UnmountResponse, error) {
var resp UnmountResponse
if err := c.doPost("/unmount", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// Configure updates runtime options such as quota for an existing mount.
func (c *Client) Configure(req *ConfigureRequest) (*ConfigureResponse, error) {
var resp ConfigureResponse
if err := c.doPost("/configure", req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
func (c *Client) doPost(path string, payload any, out any) error {
body := &bytes.Buffer{}
if err := json.NewEncoder(body).Encode(payload); err != nil {
return fmt.Errorf("encode request: %w", err)
}
req, err := http.NewRequest(http.MethodPost, c.baseURL+path, body)
if err != nil {
return fmt.Errorf("build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("call mount service: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
var errResp ErrorResponse
if err := json.NewDecoder(resp.Body).Decode(&errResp); err == nil && errResp.Error != "" {
return errors.New(errResp.Error)
}
data, _ := io.ReadAll(resp.Body)
return fmt.Errorf("mount service error: %s (%s)", resp.Status, string(data))
}
if out == nil {
_, _ = io.Copy(io.Discard, resp.Body)
return nil
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("decode response: %w", err)
}
return nil
}
|