File: client.go

package info (click to toggle)
golang-github-containerd-nydus-snapshotter 0.13.4-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,824 kB
  • sloc: sh: 470; makefile: 129
file content (343 lines) | stat: -rw-r--r-- 8,977 bytes parent folder | download
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
 * Copyright (c) 2020. Ant Group. All rights reserved.
 * Copyright (c) 2022. Nydus Developers. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

package daemon

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/fs"
	"net"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/pkg/errors"

	"github.com/containerd/containerd/log"
	"github.com/containerd/nydus-snapshotter/pkg/daemon/types"
	"github.com/containerd/nydus-snapshotter/pkg/metrics/tool"
	"github.com/containerd/nydus-snapshotter/pkg/utils/retry"
)

const (
	// Get information about nydus daemon
	endpointDaemonInfo = "/api/v1/daemon"
	// Mount or umount filesystems.
	endpointMount = "/api/v1/mount"
	// Fetch generic filesystem metrics.
	endpointMetrics = "/api/v1/metrics"
	// Fetch metrics relevant to caches usage.
	endpointCacheMetrics = "/api/v1/metrics/blobcache"
	// Fetch metrics about inflighting operations.
	endpointInflightMetrics = "/api/v1/metrics/inflight"
	// Request nydus daemon to retrieve its runtime states from the supervisor, recovering states for failover.
	endpointTakeOver = "/api/v1/daemon/fuse/takeover"
	// Request nydus daemon to send its runtime states to the supervisor, preparing for failover.
	endpointSendFd = "/api/v1/daemon/fuse/sendfd"
	// Request nydus daemon to start filesystem service.
	endpointStart = "/api/v1/daemon/start"
	// Request nydus daemon to exit
	endpointExit = "/api/v1/daemon/exit"

	// --- V2 API begins
	// Add/remove blobs managed by the blob cache manager.
	endpointBlobs = "/api/v2/blobs"

	defaultHTTPClientTimeout = 30 * time.Second

	jsonContentType = "application/json"
)

// Nydusd HTTP client to query nydusd runtime status, operate file system instances.
// Control nydusd workflow like failover and upgrade.
type NydusdClient interface {
	GetDaemonInfo() (*types.DaemonInfo, error)

	Mount(mountpoint, bootstrap, daemonConfig string) error
	Umount(mountpoint string) error

	BindBlob(daemonConfig string) error
	UnbindBlob(domainID, blobID string) error

	GetFsMetrics(sid string) (*types.FsMetrics, error)
	GetInflightMetrics() (*types.InflightMetrics, error)
	GetCacheMetrics(sid string) (*types.CacheMetrics, error)

	TakeOver() error
	SendFd() error
	Start() error
	Exit() error
}

// Nydusd API server http client used to command nydusd's action and
// query nydusd working status.
type nydusdClient struct {
	httpClient *http.Client
}

type query = url.Values

func (c *nydusdClient) url(path string, query query) (url string) {
	url = fmt.Sprintf("http://unix%s", path)

	if len(query) != 0 {
		url += "?" + query.Encode()
	}

	return
}

// A simple http client request wrapper with capability to take
// request body and handle or process http response if result is expected.
func (c *nydusdClient) request(method string, url string,
	body io.Reader, respHandler func(resp *http.Response) error) error {

	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return errors.Wrapf(err, "construct request %s", url)
	}

	if body != nil {
		req.Header.Add("Content-Type", jsonContentType)
	}

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if succeeded(resp) {
		if respHandler != nil {
			if err = respHandler(resp); err != nil {
				return errors.Wrapf(err, "handle response")
			}
		}
		return nil
	}

	return parseErrorMessage(resp)
}

func succeeded(resp *http.Response) bool {
	return resp.StatusCode == http.StatusNoContent || resp.StatusCode == http.StatusOK
}

func decode(resp *http.Response, v any) error {
	if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
		return errors.Wrap(err, "decode response")
	}

	return nil
}

// Parse http response to get the specific error message formatted by nydusd API server.
// So it will be clear what's wrong in nydusd during processing http requests.
func parseErrorMessage(resp *http.Response) error {
	var errMessage types.ErrorMessage
	err := decode(resp, &errMessage)
	if err != nil {
		return err
	}

	return errors.Errorf("http response: %d, error code: %s, error message: %s",
		resp.StatusCode, errMessage.Code, errMessage.Message)
}

func buildTransport(sock string) http.RoundTripper {
	return &http.Transport{
		MaxIdleConns:          10,
		IdleConnTimeout:       10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
			dialer := &net.Dialer{
				Timeout:   5 * time.Second,
				KeepAlive: 5 * time.Second,
			}
			return dialer.DialContext(ctx, "unix", sock)
		},
	}
}

func WaitUntilSocketExisted(sock string, pid int) error {
	return retry.Do(func() (err error) {
		var st fs.FileInfo
		if st, err = os.Stat(sock); err != nil {
			return
		}

		if st.Mode()&os.ModeSocket == 0 {
			return errors.Errorf("file %s is not socket file", sock)
		}

		return nil
	},
		retry.Attempts(100), // totally wait for 10 seconds, should be enough
		retry.LastErrorOnly(true),
		retry.Delay(100*time.Millisecond),
		retry.OnlyRetryIf(func(error) bool {
			zombie, err := tool.IsZombieProcess(pid)
			if err != nil {
				return false
			}
			// Stop retry if nydus daemon process is already in Zombie state.
			if zombie {
				log.L.Errorf("Process %d has been a zombie", pid)
				return true
			}
			return false
		}),
	)
}

func NewNydusClient(sock string) (NydusdClient, error) {
	transport := buildTransport(sock)
	return &nydusdClient{
		httpClient: &http.Client{
			Timeout:   defaultHTTPClientTimeout,
			Transport: transport,
		},
	}, nil
}

func (c *nydusdClient) GetDaemonInfo() (*types.DaemonInfo, error) {
	url := c.url(endpointDaemonInfo, query{})

	var info types.DaemonInfo
	err := c.request(http.MethodGet, url, nil, func(resp *http.Response) error {
		if err := decode(resp, &info); err != nil {
			return err
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	return &info, nil
}

func (c *nydusdClient) Mount(mp, bootstrap, mountConfig string) error {
	cmd, err := json.Marshal(types.NewMountRequest(bootstrap, mountConfig))
	if err != nil {
		return errors.Wrap(err, "construct mount request")
	}

	query := query{}
	query.Add("mountpoint", mp)
	url := c.url(endpointMount, query)

	return c.request(http.MethodPost, url, bytes.NewBuffer(cmd), nil)
}

func (c *nydusdClient) Umount(mp string) error {
	query := query{}
	query.Add("mountpoint", mp)
	url := c.url(endpointMount, query)
	return c.request(http.MethodDelete, url, nil, nil)
}

func (c *nydusdClient) BindBlob(daemonConfig string) error {
	url := c.url(endpointBlobs, query{})
	return c.request(http.MethodPut, url, bytes.NewBuffer([]byte(daemonConfig)), nil)
}

// Delete /api/v2/blobs implements different functions according to different parameters
//  1. domainID , delete all blob entries in the domain.
//  2. domainID + blobID, delete the blob entry, if the blob is bootstrap
//     also delete blob entries belong to it.
//  3. blobID, try to find and cull blob cache files by blobID in all domains.
func (c *nydusdClient) UnbindBlob(domainID, blobID string) error {
	query := query{}
	if domainID != "" {
		query.Add("domain_id", domainID)
		if domainID != blobID {
			query.Add("blob_id", blobID)
		}
	} else {
		query.Add("blob_id", blobID)
	}

	url := c.url(endpointBlobs, query)

	return c.request(http.MethodDelete, url, nil, nil)
}

func (c *nydusdClient) GetFsMetrics(sid string) (*types.FsMetrics, error) {
	query := query{}
	if sid != "" {
		query.Add("id", "/"+sid)
	}

	url := c.url(endpointMetrics, query)
	var m types.FsMetrics
	if err := c.request(http.MethodGet, url, nil, func(resp *http.Response) error {
		return decode(resp, &m)
	}); err != nil {
		return nil, err
	}

	return &m, nil
}

func (c *nydusdClient) GetInflightMetrics() (*types.InflightMetrics, error) {
	url := c.url(endpointInflightMetrics, query{})
	var m types.InflightMetrics
	if err := c.request(http.MethodGet, url, nil, func(resp *http.Response) error {
		if resp.StatusCode != http.StatusNoContent {
			return decode(resp, &m.Values)
		}
		return nil
	}); err != nil {
		return nil, err
	}

	return &m, nil
}

func (c *nydusdClient) GetCacheMetrics(sid string) (*types.CacheMetrics, error) {
	query := query{}
	if sid != "" {
		query.Add("id", "/"+sid)
	}

	url := c.url(endpointCacheMetrics, query)
	var m types.CacheMetrics
	if err := c.request(http.MethodGet, url, nil, func(resp *http.Response) error {
		return decode(resp, &m)
	}); err != nil {
		return nil, err
	}

	return &m, nil
}

func (c *nydusdClient) TakeOver() error {
	url := c.url(endpointTakeOver, query{})
	return c.request(http.MethodPut, url, nil, nil)
}

func (c *nydusdClient) SendFd() error {
	url := c.url(endpointSendFd, query{})
	return c.request(http.MethodPut, url, nil, nil)
}

func (c *nydusdClient) Start() error {
	url := c.url(endpointStart, query{})
	return c.request(http.MethodPut, url, nil, nil)
}

func (c *nydusdClient) Exit() error {
	url := c.url(endpointExit, query{})
	return c.request(http.MethodPut, url, nil, nil)
}