| 1 |
// A REST client to interact with LINSTOR's REST API |
| 2 |
// Copyright (C) LINBIT HA-Solutions GmbH |
| 3 |
// All Rights Reserved. |
| 4 |
// Author: Roland Kammerer <[email protected]> |
| 5 |
// |
| 6 |
// Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 7 |
// not use this file except in compliance with the License. You may obtain |
| 8 |
// a copy of the License at |
| 9 |
// |
| 10 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
// |
| 12 |
// Unless required by applicable law or agreed to in writing, software |
| 13 |
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 14 |
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 15 |
// License for the specific language governing permissions and limitations |
| 16 |
// under the License. |
| 17 |
|
| 18 |
package client |
| 19 |
|
| 20 |
import ( |
| 21 |
"bytes" |
| 22 |
"context" |
| 23 |
"crypto/tls" |
| 24 |
"crypto/x509" |
| 25 |
"encoding/json" |
| 26 |
"errors" |
| 27 |
"fmt" |
| 28 |
"io" |
| 29 |
"log" |
| 30 |
"net" |
| 31 |
"net/http" |
| 32 |
"net/url" |
| 33 |
"os" |
| 34 |
"strings" |
| 35 |
"sync" |
| 36 |
"time" |
| 37 |
|
| 38 |
"github.com/donovanhide/eventsource" |
| 39 |
"golang.org/x/time/rate" |
| 40 |
"moul.io/http2curl/v2" |
| 41 |
|
| 42 |
linstor "github.com/LINBIT/golinstor" |
| 43 |
) |
| 44 |
|
| 45 |
// Client is a struct representing a LINSTOR REST client. |
| 46 |
type Client struct { |
| 47 |
httpClient *http.Client |
| 48 |
basicAuth *BasicAuthCfg |
| 49 |
bearerToken string |
| 50 |
userAgent string |
| 51 |
controllersMu sync.Mutex |
| 52 |
controllers []*url.URL |
| 53 |
lim *rate.Limiter |
| 54 |
log interface{} // must be either Logger or LeveledLogger |
| 55 |
|
| 56 |
Nodes NodeProvider |
| 57 |
ResourceDefinitions ResourceDefinitionProvider |
| 58 |
Resources ResourceProvider |
| 59 |
ResourceGroups ResourceGroupProvider |
| 60 |
StoragePoolDefinitions StoragePoolDefinitionProvider |
| 61 |
Encryption EncryptionProvider |
| 62 |
Controller ControllerProvider |
| 63 |
Events EventProvider |
| 64 |
Remote RemoteProvider |
| 65 |
Backup BackupProvider |
| 66 |
KeyValueStore KeyValueStoreProvider |
| 67 |
Connections ConnectionProvider |
| 68 |
} |
| 69 |
|
| 70 |
// Logger represents a standard logger interface |
| 71 |
type Logger interface { |
| 72 |
Printf(string, ...interface{}) |
| 73 |
} |
| 74 |
|
| 75 |
// LeveledLogger interface implements the basic methods that a logger library needs |
| 76 |
type LeveledLogger interface { |
| 77 |
Errorf(string, ...interface{}) |
| 78 |
Infof(string, ...interface{}) |
| 79 |
Debugf(string, ...interface{}) |
| 80 |
Warnf(string, ...interface{}) |
| 81 |
} |
| 82 |
|
| 83 |
type BasicAuthCfg struct { |
| 84 |
Username, Password string |
| 85 |
} |
| 86 |
|
| 87 |
// const errors as in https://dave.cheney.net/2016/04/07/constant-errors |
| 88 |
type clientError string |
| 89 |
|
| 90 |
func (e clientError) Error() string { return string(e) } |
| 91 |
|
| 92 |
const ( |
| 93 |
// NotFoundError is the error type returned in case of a 404 error. This is required to test for this kind of error. |
| 94 |
NotFoundError = clientError("404 Not Found") |
| 95 |
// Name of the environment variable that stores the certificate used for TLS client authentication |
| 96 |
UserCertEnv = "LS_USER_CERTIFICATE" |
| 97 |
// Name of the environment variable that stores the path to the certificate used for TLS client authentication |
| 98 |
UserCertFileEnv = "LS_USER_CERTIFICATE_FILE" |
| 99 |
// Name of the environment variable that stores the key used for TLS client authentication |
| 100 |
UserKeyEnv = "LS_USER_KEY" |
| 101 |
// Name of the environment variable that stores the path to the key used for TLS client authentication |
| 102 |
UserKeyFileEnv = "LS_USER_KEY_FILE" |
| 103 |
// Name of the environment variable that stores the certificate authority for the LINSTOR HTTPS API |
| 104 |
RootCAEnv = "LS_ROOT_CA" |
| 105 |
// Name of the environment variable that stores the path to the certificate authority for the LINSTOR HTTPS API |
| 106 |
RootCAFileEnv = "LS_ROOT_CA_FILE" |
| 107 |
// Name of the environment variable that holds the URL(s) of LINSTOR controllers |
| 108 |
ControllerUrlEnv = "LS_CONTROLLERS" |
| 109 |
// Name of the environment variable that holds the username for authentication |
| 110 |
UsernameEnv = "LS_USERNAME" |
| 111 |
// Name of the environment variable that holds the password for authentication |
| 112 |
PasswordEnv = "LS_PASSWORD" |
| 113 |
// Name of the environment variable that points to the file containing the token for authentication |
| 114 |
BearerTokenFileEnv = "LS_BEARER_TOKEN_FILE" |
| 115 |
) |
| 116 |
|
| 117 |
// For example: |
| 118 |
// u, _ := url.Parse("http://somehost:3370") |
| 119 |
// c, _ := linstor.NewClient(linstor.BaseURL(u)) |
| 120 |
|
| 121 |
// Option configures a LINSTOR Client |
| 122 |
type Option func(*Client) error |
| 123 |
|
| 124 |
// BaseURL is a client's option to set the baseURL of the REST client. |
| 125 |
// |
| 126 |
// If multiple URLs are provided, each is tried in turn. |
| 127 |
func BaseURL(urls ...*url.URL) Option { |
| 128 |
return func(c *Client) error { |
| 129 |
c.controllers = urls |
| 130 |
return nil |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
// BasicAuth is a client's option to set username and password for the REST client. |
| 135 |
func BasicAuth(basicauth *BasicAuthCfg) Option { |
| 136 |
return func(c *Client) error { |
| 137 |
c.basicAuth = basicauth |
| 138 |
return nil |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
// HTTPClient is a client's option to set a specific http.Client. |
| 143 |
func HTTPClient(httpClient *http.Client) Option { |
| 144 |
return func(c *Client) error { |
| 145 |
c.httpClient = httpClient |
| 146 |
return nil |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
// Log is a client's option to set a Logger |
| 151 |
func Log(logger interface{}) Option { |
| 152 |
return func(c *Client) error { |
| 153 |
switch logger.(type) { |
| 154 |
case Logger, LeveledLogger, nil: |
| 155 |
c.log = logger |
| 156 |
default: |
| 157 |
return errors.New("invalid logger type, expected Logger or LeveledLogger") |
| 158 |
} |
| 159 |
return nil |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
// Limiter to use when making queries. |
| 164 |
// Mutually exclusive with Limit, last applied option wins. |
| 165 |
func Limiter(limiter *rate.Limiter) Option { |
| 166 |
return func(c *Client) error { |
| 167 |
if limiter.Burst() == 0 && limiter.Limit() != rate.Inf { |
| 168 |
return fmt.Errorf("invalid rate limit, burst must not be zero for non-unlimited rates") |
| 169 |
} |
| 170 |
c.lim = limiter |
| 171 |
return nil |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
// Limit is the client's option to set number of requests per second and |
| 176 |
// max number of bursts. |
| 177 |
// Mutually exclusive with Limiter, last applied option wins. |
| 178 |
// Deprecated: Use Limiter instead. |
| 179 |
func Limit(r rate.Limit, b int) Option { |
| 180 |
return Limiter(rate.NewLimiter(r, b)) |
| 181 |
} |
| 182 |
|
| 183 |
func Controllers(controllers []string) Option { |
| 184 |
return func(c *Client) error { |
| 185 |
var err error |
| 186 |
c.controllers, err = parseURLs(controllers) |
| 187 |
return err |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
// BearerToken configures authentication via the given token send in the Authorization Header. |
| 192 |
// If set, this will override any authentication happening via Basic Authentication. |
| 193 |
func BearerToken(token string) Option { |
| 194 |
return func(c *Client) error { |
| 195 |
c.bearerToken = token |
| 196 |
return nil |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
// BearerTokenFromFile reads a bearer token from the given file path. |
| 201 |
// If no path is given, the default is /var/lib/linstor.d/auth.json. |
| 202 |
func BearerTokenFromFile(path ...string) Option { |
| 203 |
return func(c *Client) error { |
| 204 |
p := "/var/lib/linstor.d/auth.json" |
| 205 |
if len(path) > 0 { |
| 206 |
p = path[0] |
| 207 |
} |
| 208 |
|
| 209 |
token, err := tokenFromFile(p) |
| 210 |
if err != nil { |
| 211 |
return err |
| 212 |
} |
| 213 |
|
| 214 |
c.bearerToken = token |
| 215 |
return nil |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
// UserAgent sets the User-Agent header for every request to the given string. |
| 220 |
func UserAgent(ua string) Option { |
| 221 |
return func(c *Client) error { |
| 222 |
c.userAgent = ua |
| 223 |
return nil |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
// buildHttpClient constructs an HTTP client which will be used to connect to |
| 228 |
// the LINSTOR controller. It recongnizes some environment variables which can |
| 229 |
// be used to configure the HTTP client at runtime. If an invalid key or |
| 230 |
// certificate is passed, an error is returned. |
| 231 |
// If none or not all of the environment variables are passed, the default |
| 232 |
// client is used as a fallback. |
| 233 |
func buildHttpClient() (*http.Client, error) { |
| 234 |
certFilePath, certFile := os.LookupEnv(UserCertFileEnv) |
| 235 |
certPEM, cert := os.LookupEnv(UserCertEnv) |
| 236 |
keyFilePath, keyFile := os.LookupEnv(UserKeyFileEnv) |
| 237 |
keyPEM, key := os.LookupEnv(UserKeyEnv) |
| 238 |
caFilePath, caFile := os.LookupEnv(RootCAFileEnv) |
| 239 |
caPEM, ca := os.LookupEnv(RootCAEnv) |
| 240 |
|
| 241 |
if (key || keyFile) != (cert || certFile) { |
| 242 |
return nil, fmt.Errorf("'%s[_FILE]', '%s[_FILE]': specify both or none", UserKeyEnv, UserCertEnv) |
| 243 |
} |
| 244 |
|
| 245 |
if !cert && !certFile && !key && !keyFile && !ca && !caFile { |
| 246 |
// None of the special variables was set -> if TLS is used, default configuration can be used |
| 247 |
return http.DefaultClient, nil |
| 248 |
} |
| 249 |
|
| 250 |
tlsConfig := &tls.Config{} |
| 251 |
|
| 252 |
if caFile { |
| 253 |
pem, err := os.ReadFile(caFilePath) |
| 254 |
if err != nil { |
| 255 |
return nil, fmt.Errorf("failed to read CA file: %s", err) |
| 256 |
} |
| 257 |
caPEM = string(pem) |
| 258 |
ca = true |
| 259 |
} |
| 260 |
|
| 261 |
if ca { |
| 262 |
caPool := x509.NewCertPool() |
| 263 |
ok := caPool.AppendCertsFromPEM([]byte(caPEM)) |
| 264 |
if !ok { |
| 265 |
return nil, fmt.Errorf("failed to get a valid certificate from '%s'", RootCAEnv) |
| 266 |
} |
| 267 |
tlsConfig.RootCAs = caPool |
| 268 |
} |
| 269 |
|
| 270 |
if (key || keyFile) && (cert || certFile) { |
| 271 |
tlsConfig.GetClientCertificate = func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) { |
| 272 |
if keyFile { |
| 273 |
pem, err := os.ReadFile(keyFilePath) |
| 274 |
if err != nil { |
| 275 |
return nil, fmt.Errorf("failed to read key file: %s", err) |
| 276 |
} |
| 277 |
|
| 278 |
keyPEM = string(pem) |
| 279 |
} |
| 280 |
|
| 281 |
if certFile { |
| 282 |
pem, err := os.ReadFile(certFilePath) |
| 283 |
if err != nil { |
| 284 |
return nil, fmt.Errorf("failed to read certificate file: %s", err) |
| 285 |
} |
| 286 |
|
| 287 |
certPEM = string(pem) |
| 288 |
} |
| 289 |
|
| 290 |
cert, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM)) |
| 291 |
if err != nil { |
| 292 |
return nil, fmt.Errorf("failed to load certificate: %s", err) |
| 293 |
} |
| 294 |
|
| 295 |
return &cert, nil |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
if key && cert { |
| 300 |
keyPair, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM)) |
| 301 |
if err != nil { |
| 302 |
return nil, fmt.Errorf("failed to load keys: %w", err) |
| 303 |
} |
| 304 |
tlsConfig.Certificates = append(tlsConfig.Certificates, keyPair) |
| 305 |
} |
| 306 |
|
| 307 |
return &http.Client{ |
| 308 |
Transport: &http.Transport{ |
| 309 |
TLSClientConfig: tlsConfig, |
| 310 |
}, |
| 311 |
}, nil |
| 312 |
} |
| 313 |
|
| 314 |
// Return the default scheme to access linstor |
| 315 |
// If one of the HTTPS environment variables is set, will return "https". |
| 316 |
// If not, will return "http" |
| 317 |
func defaultScheme() string { |
| 318 |
for _, env := range []string{ |
| 319 |
RootCAEnv, |
| 320 |
RootCAFileEnv, |
| 321 |
UserCertEnv, |
| 322 |
UserCertFileEnv, |
| 323 |
UserKeyEnv, |
| 324 |
UserKeyFileEnv, |
| 325 |
} { |
| 326 |
if _, ok := os.LookupEnv(env); ok { |
| 327 |
return "https" |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
return "http" |
| 332 |
} |
| 333 |
|
| 334 |
const defaultHost = "localhost" |
| 335 |
|
| 336 |
// Return the default port to access linstor. |
| 337 |
// Defaults are: |
| 338 |
// "https": 3371 |
| 339 |
// "http": 3370 |
| 340 |
func defaultPort(scheme string) string { |
| 341 |
if scheme == "https" { |
| 342 |
return "3371" |
| 343 |
} |
| 344 |
return "3370" |
| 345 |
} |
| 346 |
|
| 347 |
func parseBaseURL(urlString string) (*url.URL, error) { |
| 348 |
u, err := url.Parse(urlString) |
| 349 |
if err != nil { |
| 350 |
return nil, err |
| 351 |
} |
| 352 |
|
| 353 |
if u.Path != "" && u.Host == "" { |
| 354 |
u.Host = u.Path |
| 355 |
u.Path = "" |
| 356 |
} |
| 357 |
|
| 358 |
if u.Host == "" && u.Scheme != "" { |
| 359 |
u.Host = fmt.Sprintf("%s:%s", u.Scheme, u.Opaque) |
| 360 |
u.Scheme = "" |
| 361 |
u.Opaque = "" |
| 362 |
} |
| 363 |
|
| 364 |
switch u.Scheme { |
| 365 |
case "", "linstor": |
| 366 |
u.Scheme = defaultScheme() |
| 367 |
case "linstor+ssl": |
| 368 |
u.Scheme = "https" |
| 369 |
} |
| 370 |
|
| 371 |
if u.Port() == "" { |
| 372 |
u.Host = fmt.Sprintf("%s:%s", u.Hostname(), defaultPort(u.Scheme)) |
| 373 |
} |
| 374 |
|
| 375 |
return u, nil |
| 376 |
} |
| 377 |
|
| 378 |
func parseURLs(urls []string) ([]*url.URL, error) { |
| 379 |
var result []*url.URL |
| 380 |
for _, controller := range urls { |
| 381 |
url, err := parseBaseURL(controller) |
| 382 |
if err != nil { |
| 383 |
return nil, err |
| 384 |
} |
| 385 |
result = append(result, url) |
| 386 |
} |
| 387 |
|
| 388 |
return result, nil |
| 389 |
} |
| 390 |
|
| 391 |
// NewClient takes an arbitrary number of options and returns a Client or an error. |
| 392 |
// It recognizes several environment variables which can be used to configure |
| 393 |
// the client at runtime: |
| 394 |
// |
| 395 |
// - LS_CONTROLLERS: a comma-separated list of LINSTOR controllers to connect to. |
| 396 |
// |
| 397 |
// - LS_USERNAME, LS_PASSWORD: can be used to authenticate against the LINSTOR |
| 398 |
// controller using HTTP basic authentication. |
| 399 |
// |
| 400 |
// - LS_USER_CERTIFICATE, LS_USER_KEY, LS_ROOT_CA: can be used to enable TLS on |
| 401 |
// the HTTP client, enabling encrypted communication with the LINSTOR controller. |
| 402 |
// |
| 403 |
// - LS_USER_CERTIFICATE_FILE, LS_USER_KEY_FILE, LS_ROOT_CA_FILE: can be used to |
| 404 |
// enable TLS on the HTTP client. Instead of expecting the PEM certificates directly, |
| 405 |
// this expects a path to the certificates instead. |
| 406 |
// |
| 407 |
// - LS_BEARER_TOKEN_FILE: can be set to a file containing the bearer token used |
| 408 |
// for authentication. |
| 409 |
// |
| 410 |
// Options passed to NewClient take precedence over options passed in via |
| 411 |
// environment variables. |
| 412 |
func NewClient(options ...Option) (*Client, error) { |
| 413 |
httpClient, err := buildHttpClient() |
| 414 |
if err != nil { |
| 415 |
return nil, fmt.Errorf("failed to build http client: %w", err) |
| 416 |
} |
| 417 |
|
| 418 |
c := &Client{ |
| 419 |
httpClient: httpClient, |
| 420 |
basicAuth: &BasicAuthCfg{ |
| 421 |
Username: os.Getenv(UsernameEnv), |
| 422 |
Password: os.Getenv(PasswordEnv), |
| 423 |
}, |
| 424 |
lim: rate.NewLimiter(rate.Inf, 0), |
| 425 |
log: log.New(os.Stderr, "", 0), |
| 426 |
} |
| 427 |
|
| 428 |
c.Nodes = &NodeService{client: c} |
| 429 |
c.ResourceDefinitions = &ResourceDefinitionService{client: c} |
| 430 |
c.Resources = &ResourceService{client: c} |
| 431 |
c.Encryption = &EncryptionService{client: c} |
| 432 |
c.ResourceGroups = &ResourceGroupService{client: c} |
| 433 |
c.StoragePoolDefinitions = &StoragePoolDefinitionService{client: c} |
| 434 |
c.Controller = &ControllerService{client: c} |
| 435 |
c.Events = &EventService{client: c} |
| 436 |
c.Remote = &RemoteService{client: c} |
| 437 |
c.Backup = &BackupService{client: c} |
| 438 |
c.KeyValueStore = &KeyValueStoreService{client: c} |
| 439 |
c.Connections = &ConnectionService{client: c} |
| 440 |
|
| 441 |
if path, ok := os.LookupEnv(BearerTokenFileEnv); ok { |
| 442 |
token, err := tokenFromFile(path) |
| 443 |
if err != nil { |
| 444 |
return nil, fmt.Errorf("failed to read token from file: %w", err) |
| 445 |
} |
| 446 |
|
| 447 |
c.bearerToken = token |
| 448 |
} |
| 449 |
|
| 450 |
for _, opt := range options { |
| 451 |
if err := opt(c); err != nil { |
| 452 |
return nil, err |
| 453 |
} |
| 454 |
} |
| 455 |
|
| 456 |
if len(c.controllers) == 0 { |
| 457 |
// if not already set by option, get from environment... |
| 458 |
controllersStr := os.Getenv(ControllerUrlEnv) |
| 459 |
if controllersStr == "" { |
| 460 |
// ... or fall back to defaults |
| 461 |
controllersStr = fmt.Sprintf("%v://%v:%v", defaultScheme(), defaultHost, defaultPort(defaultScheme())) |
| 462 |
} |
| 463 |
|
| 464 |
c.controllers, err = parseURLs(strings.Split(controllersStr, ",")) |
| 465 |
if err != nil { |
| 466 |
return nil, fmt.Errorf("failed to parse controller URLs: %w", err) |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
return c, nil |
| 471 |
} |
| 472 |
|
| 473 |
// tokenFromFile reads a token from the file at path. If the file contains |
| 474 |
// valid JSON with a "token" key, the value of that key is returned. |
| 475 |
// Otherwise, the entire file content is returned as the token. |
| 476 |
func tokenFromFile(path string) (string, error) { |
| 477 |
content, err := os.ReadFile(path) |
| 478 |
if err != nil { |
| 479 |
return "", err |
| 480 |
} |
| 481 |
|
| 482 |
var parsed map[string]interface{} |
| 483 |
if err := json.Unmarshal(content, &parsed); err == nil { |
| 484 |
if token, ok := parsed["token"]; ok { |
| 485 |
if s, ok := token.(string); ok { |
| 486 |
return s, nil |
| 487 |
} |
| 488 |
} |
| 489 |
} |
| 490 |
|
| 491 |
return strings.TrimSpace(string(content)), nil |
| 492 |
} |
| 493 |
|
| 494 |
// BaseURL returns the current controllers URL. |
| 495 |
func (c *Client) BaseURL() *url.URL { |
| 496 |
c.controllersMu.Lock() |
| 497 |
defer c.controllersMu.Unlock() |
| 498 |
return c.controllers[0] |
| 499 |
} |
| 500 |
|
| 501 |
func (c *Client) newRequest(method, path string, body interface{}) (*http.Request, error) { |
| 502 |
rel, err := url.Parse(path) |
| 503 |
if err != nil { |
| 504 |
return nil, err |
| 505 |
} |
| 506 |
|
| 507 |
u := c.BaseURL().ResolveReference(rel) |
| 508 |
|
| 509 |
var buf io.ReadWriter |
| 510 |
if body != nil { |
| 511 |
// Use json.Marshal instead of encoding to the buffer directly; json.Encoder.Encode() adds a newline |
| 512 |
// at the end, which is annoying for logging. |
| 513 |
jsonBuf, err := json.Marshal(body) |
| 514 |
if err != nil { |
| 515 |
return nil, fmt.Errorf("failed to marshal JSON body: %w", err) |
| 516 |
} |
| 517 |
buf = bytes.NewBuffer(jsonBuf) |
| 518 |
} |
| 519 |
|
| 520 |
req, err := http.NewRequest(method, u.String(), buf) |
| 521 |
if err != nil { |
| 522 |
return nil, err |
| 523 |
} |
| 524 |
|
| 525 |
if body != nil { |
| 526 |
req.Header.Set("Content-Type", "application/json") |
| 527 |
} |
| 528 |
|
| 529 |
if c.userAgent != "" { |
| 530 |
req.Header.Set("User-Agent", c.userAgent) |
| 531 |
} |
| 532 |
|
| 533 |
username := c.basicAuth.Username |
| 534 |
if username != "" { |
| 535 |
req.SetBasicAuth(username, c.basicAuth.Password) |
| 536 |
} |
| 537 |
|
| 538 |
if c.bearerToken != "" { |
| 539 |
req.Header.Set("Authorization", "Bearer "+c.bearerToken) |
| 540 |
} |
| 541 |
|
| 542 |
return req, nil |
| 543 |
} |
| 544 |
|
| 545 |
func (c *Client) curlify(req *http.Request) (string, error) { |
| 546 |
cc, err := http2curl.GetCurlCommand(req) |
| 547 |
if err != nil { |
| 548 |
return "", err |
| 549 |
} |
| 550 |
return cc.String(), nil |
| 551 |
} |
| 552 |
|
| 553 |
// findRespondingController scans the list of controllers for a working LINSTOR controller. |
| 554 |
// |
| 555 |
// After this returns successfully, the first controllers entry will point to the working controller. |
| 556 |
// |
| 557 |
// If no controller could be reached, an error combining all attempts is returned. |
| 558 |
func (c *Client) findRespondingController() error { |
| 559 |
if len(c.controllers) <= 1 { |
| 560 |
return nil |
| 561 |
} |
| 562 |
|
| 563 |
c.controllersMu.Lock() |
| 564 |
defer c.controllersMu.Unlock() |
| 565 |
|
| 566 |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 567 |
|
| 568 |
errs := make([]error, len(c.controllers)) |
| 569 |
var wg sync.WaitGroup |
| 570 |
wg.Add(len(c.controllers)) |
| 571 |
for i := range c.controllers { |
| 572 |
i := i |
| 573 |
go func() { |
| 574 |
defer wg.Done() |
| 575 |
conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", c.controllers[i].Host) |
| 576 |
if err != nil { |
| 577 |
errs[i] = fmt.Errorf("failed to dial '%s': %w", c.controllers[i].Host, err) |
| 578 |
return |
| 579 |
} |
| 580 |
_ = conn.Close() |
| 581 |
// Success -> we can cancel the other goroutines |
| 582 |
cancel() |
| 583 |
}() |
| 584 |
} |
| 585 |
|
| 586 |
wg.Wait() |
| 587 |
cancel() // just to make linters happy |
| 588 |
|
| 589 |
for i := range errs { |
| 590 |
if errs[i] == nil { |
| 591 |
tmp := c.controllers[i] |
| 592 |
c.controllers[i] = c.controllers[0] |
| 593 |
c.controllers[0] = tmp |
| 594 |
return nil |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
return fmt.Errorf("could not connect to any controller: %w", errors.Join(errs...)) |
| 599 |
} |
| 600 |
|
| 601 |
func (c *Client) logCurlify(req *http.Request) { |
| 602 |
var msg string |
| 603 |
if curl, err := c.curlify(req); err != nil { |
| 604 |
msg = err.Error() |
| 605 |
} else { |
| 606 |
msg = curl |
| 607 |
} |
| 608 |
|
| 609 |
switch l := c.log.(type) { |
| 610 |
case LeveledLogger: |
| 611 |
l.Debugf("%s", msg) |
| 612 |
case Logger: |
| 613 |
l.Printf("[DEBUG] %s", msg) |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
func (c *Client) retry(origErr error, req *http.Request) (*http.Response, error) { |
| 618 |
// only retry on network errors and if we even have another controller to choose from |
| 619 |
var netError net.Error |
| 620 |
if !errors.As(origErr, &netError) || len(c.controllers) <= 1 { |
| 621 |
return nil, origErr |
| 622 |
} |
| 623 |
|
| 624 |
e := c.findRespondingController() |
| 625 |
// if findRespondingController failed, or we just got the same base URL, don't bother retrying |
| 626 |
if e != nil { |
| 627 |
return nil, origErr |
| 628 |
} |
| 629 |
|
| 630 |
req.URL.Host = c.BaseURL().Host |
| 631 |
req.URL.Scheme = c.BaseURL().Scheme |
| 632 |
return c.httpClient.Do(req) |
| 633 |
} |
| 634 |
|
| 635 |
// do sends a prepared http.Request and returns the http.Response. If an HTTP error occurs, the parsed error is |
| 636 |
// returned. Otherwise, the response is returned as-is. The caller is responsible for closing the response body in |
| 637 |
// the non-error case. |
| 638 |
func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) { |
| 639 |
if err := c.lim.Wait(ctx); err != nil { |
| 640 |
return nil, err |
| 641 |
} |
| 642 |
req = req.WithContext(ctx) |
| 643 |
|
| 644 |
c.logCurlify(req) |
| 645 |
|
| 646 |
resp, err := c.httpClient.Do(req) |
| 647 |
if err != nil { |
| 648 |
select { |
| 649 |
case <-ctx.Done(): |
| 650 |
return nil, ctx.Err() |
| 651 |
default: |
| 652 |
} |
| 653 |
|
| 654 |
// if this was a connectivity issue, attempt a retry |
| 655 |
resp, err = c.retry(err, req) |
| 656 |
if err != nil { |
| 657 |
return nil, err |
| 658 |
} |
| 659 |
} |
| 660 |
|
| 661 |
if resp.StatusCode < 200 || resp.StatusCode >= 400 { |
| 662 |
// If we get an error, we handle the body ourselves, so we also have to close it. |
| 663 |
defer resp.Body.Close() //nolint:errcheck |
| 664 |
msg := fmt.Sprintf("Status code not within 200 to 400, but %d (%s)\n", |
| 665 |
resp.StatusCode, http.StatusText(resp.StatusCode)) |
| 666 |
switch l := c.log.(type) { |
| 667 |
case LeveledLogger: |
| 668 |
l.Debugf("%s", msg) |
| 669 |
case Logger: |
| 670 |
l.Printf("[DEBUG] %s", msg) |
| 671 |
} |
| 672 |
if resp.StatusCode == 404 { |
| 673 |
return nil, NotFoundError |
| 674 |
} |
| 675 |
|
| 676 |
var rets ApiCallError |
| 677 |
if err = json.NewDecoder(resp.Body).Decode(&rets); err != nil { |
| 678 |
return nil, err |
| 679 |
} |
| 680 |
return nil, rets |
| 681 |
} |
| 682 |
return resp, err |
| 683 |
} |
| 684 |
|
| 685 |
// doJSON sends a prepared http.Request and returns the http.Response. If out is provided, the response body is |
| 686 |
// JSON-decoded into out. |
| 687 |
func (c *Client) doJSON(ctx context.Context, req *http.Request, out any) (*http.Response, error) { |
| 688 |
req.Header.Set("Accept", "application/json") |
| 689 |
resp, err := c.do(ctx, req) |
| 690 |
if err != nil { |
| 691 |
return nil, err |
| 692 |
} |
| 693 |
defer resp.Body.Close() //nolint:errcheck |
| 694 |
if out != nil { |
| 695 |
err = json.NewDecoder(resp.Body).Decode(out) |
| 696 |
} |
| 697 |
return resp, err |
| 698 |
} |
| 699 |
|
| 700 |
// Higer Leve Abstractions |
| 701 |
|
| 702 |
func (c *Client) doGET(ctx context.Context, url string, ret interface{}, opts ...*ListOpts) (*http.Response, error) { |
| 703 |
opt, err := Optional(opts...) |
| 704 |
if err != nil { |
| 705 |
return nil, err |
| 706 |
} |
| 707 |
|
| 708 |
u, err := addOptions(url, opt) |
| 709 |
if err != nil { |
| 710 |
return nil, err |
| 711 |
} |
| 712 |
|
| 713 |
req, err := c.newRequest("GET", u, nil) |
| 714 |
if err != nil { |
| 715 |
return nil, err |
| 716 |
} |
| 717 |
return c.doJSON(ctx, req, ret) |
| 718 |
} |
| 719 |
|
| 720 |
func (c *Client) doEvent(ctx context.Context, url, lastEventId string) (*eventsource.Stream, error) { |
| 721 |
req, err := c.newRequest("GET", url, nil) |
| 722 |
if err != nil { |
| 723 |
return nil, err |
| 724 |
} |
| 725 |
req.Header.Set("Accept", "text/event-stream") |
| 726 |
req = req.WithContext(ctx) |
| 727 |
|
| 728 |
stream, err := eventsource.SubscribeWith(lastEventId, c.httpClient, req) |
| 729 |
if err != nil { |
| 730 |
return nil, err |
| 731 |
} |
| 732 |
|
| 733 |
return stream, nil |
| 734 |
} |
| 735 |
|
| 736 |
func (c *Client) doPOST(ctx context.Context, url string, body interface{}) (*http.Response, error) { |
| 737 |
req, err := c.newRequest("POST", url, body) |
| 738 |
if err != nil { |
| 739 |
return nil, err |
| 740 |
} |
| 741 |
|
| 742 |
return c.doJSON(ctx, req, nil) |
| 743 |
} |
| 744 |
|
| 745 |
func (c *Client) doPUT(ctx context.Context, url string, body interface{}) (*http.Response, error) { |
| 746 |
req, err := c.newRequest("PUT", url, body) |
| 747 |
if err != nil { |
| 748 |
return nil, err |
| 749 |
} |
| 750 |
|
| 751 |
return c.doJSON(ctx, req, nil) |
| 752 |
} |
| 753 |
|
| 754 |
func (c *Client) doPATCH(ctx context.Context, url string, body interface{}) (*http.Response, error) { |
| 755 |
req, err := c.newRequest("PATCH", url, body) |
| 756 |
if err != nil { |
| 757 |
return nil, err |
| 758 |
} |
| 759 |
|
| 760 |
return c.doJSON(ctx, req, nil) |
| 761 |
} |
| 762 |
|
| 763 |
func (c *Client) doDELETE(ctx context.Context, url string, body interface{}) (*http.Response, error) { |
| 764 |
req, err := c.newRequest("DELETE", url, body) |
| 765 |
if err != nil { |
| 766 |
return nil, err |
| 767 |
} |
| 768 |
|
| 769 |
return c.doJSON(ctx, req, nil) |
| 770 |
} |
| 771 |
|
| 772 |
func (c *Client) doOPTIONS(ctx context.Context, url string, ret interface{}, body interface{}) (*http.Response, error) { |
| 773 |
req, err := c.newRequest("OPTIONS", url, body) |
| 774 |
if err != nil { |
| 775 |
return nil, err |
| 776 |
} |
| 777 |
|
| 778 |
return c.doJSON(ctx, req, ret) |
| 779 |
} |
| 780 |
|
| 781 |
// ApiCallRc represents the struct returned by LINSTOR, when accessing its REST API. |
| 782 |
type ApiCallRc struct { |
| 783 |
// A masked error number |
| 784 |
RetCode int64 `json:"ret_code"` |
| 785 |
Message string `json:"message"` |
| 786 |
// Cause of the error |
| 787 |
Cause string `json:"cause,omitempty"` |
| 788 |
// Details to the error message |
| 789 |
Details string `json:"details,omitempty"` |
| 790 |
// Possible correction options |
| 791 |
Correction string `json:"correction,omitempty"` |
| 792 |
// List of error report ids related to this api call return code. |
| 793 |
ErrorReportIds []string `json:"error_report_ids,omitempty"` |
| 794 |
// Map of objection that have been involved by the operation. |
| 795 |
ObjRefs map[string]string `json:"obj_refs,omitempty"` |
| 796 |
} |
| 797 |
|
| 798 |
func (rc *ApiCallRc) String() string { |
| 799 |
s := fmt.Sprintf("Message: '%s'", rc.Message) |
| 800 |
if rc.Cause != "" { |
| 801 |
s += fmt.Sprintf("; Cause: '%s'", rc.Cause) |
| 802 |
} |
| 803 |
if rc.Details != "" { |
| 804 |
s += fmt.Sprintf("; Details: '%s'", rc.Details) |
| 805 |
} |
| 806 |
if rc.Correction != "" { |
| 807 |
s += fmt.Sprintf("; Correction: '%s'", rc.Correction) |
| 808 |
} |
| 809 |
if len(rc.ErrorReportIds) > 0 { |
| 810 |
s += fmt.Sprintf("; Reports: '[%s]'", strings.Join(rc.ErrorReportIds, ",")) |
| 811 |
} |
| 812 |
|
| 813 |
return s |
| 814 |
} |
| 815 |
|
| 816 |
// Is can be used to check the return code against a given mask. Since LINSTOR |
| 817 |
// return codes are designed to be machine readable, this can be used to check |
| 818 |
// for a very specific type of error. |
| 819 |
// Refer to package apiconsts.go in package linstor for a list of possible |
| 820 |
// mask values. |
| 821 |
func (rc *ApiCallRc) Is(mask uint64) bool { |
| 822 |
return (uint64(rc.RetCode) & (linstor.MaskError | linstor.MaskBitsCode)) == mask |
| 823 |
} |
| 824 |
|
| 825 |
// DeleteProps is a slice of properties to delete. |
| 826 |
type DeleteProps []string |
| 827 |
|
| 828 |
// OverrideProps is a map of properties to modify (key/value pairs) |
| 829 |
type OverrideProps map[string]string |
| 830 |
|
| 831 |
// Namespaces to delete |
| 832 |
type DeleteNamespaces []string |
| 833 |
|
| 834 |
// GenericPropsModify is a struct combining DeleteProps and OverrideProps |
| 835 |
type GenericPropsModify struct { |
| 836 |
DeleteProps DeleteProps `json:"delete_props,omitempty"` |
| 837 |
OverrideProps OverrideProps `json:"override_props,omitempty"` |
| 838 |
DeleteNamespaces DeleteNamespaces `json:"delete_namespaces,omitempty"` |
| 839 |
} |