Spaces:
Running
Running
File size: 10,676 Bytes
b110593 |
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 |
// _ _
// __ _____ __ ___ ___ __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
// \ V V / __/ (_| |\ V /| | (_| | || __/
// \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
// Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
//
// CONTACT: [email protected]
//
package clients
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"time"
"github.com/go-openapi/strfmt"
"github.com/weaviate/weaviate/adapters/handlers/rest/clusterapi"
"github.com/weaviate/weaviate/entities/additional"
"github.com/weaviate/weaviate/entities/search"
"github.com/weaviate/weaviate/entities/storobj"
"github.com/weaviate/weaviate/usecases/objects"
"github.com/weaviate/weaviate/usecases/replica"
)
// ReplicationClient is to coordinate operations among replicas
type replicationClient retryClient
func NewReplicationClient(httpClient *http.Client) replica.Client {
return &replicationClient{
client: httpClient,
retryer: newRetryer(),
}
}
// FetchObject fetches one object it exits
func (c *replicationClient) FetchObject(ctx context.Context, host, index,
shard string, id strfmt.UUID, selectProps search.SelectProperties,
additional additional.Properties,
) (objects.Replica, error) {
resp := objects.Replica{}
req, err := newHttpReplicaRequest(ctx, http.MethodGet, host, index, shard, "", id.String(), nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
err = c.doCustomUnmarshal(c.timeoutUnit*20, req, nil, resp.UnmarshalBinary)
return resp, err
}
func (c *replicationClient) DigestObjects(ctx context.Context,
host, index, shard string, ids []strfmt.UUID,
) (result []replica.RepairResponse, err error) {
var resp []replica.RepairResponse
body, err := json.Marshal(ids)
if err != nil {
return nil, fmt.Errorf("marshal digest objects input: %w", err)
}
req, err := newHttpReplicaRequest(
ctx, http.MethodGet, host, index, shard,
"", "_digest", bytes.NewReader(body))
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
err = c.do(c.timeoutUnit*20, req, body, &resp)
return resp, err
}
func (c *replicationClient) OverwriteObjects(ctx context.Context,
host, index, shard string, vobjects []*objects.VObject,
) ([]replica.RepairResponse, error) {
var resp []replica.RepairResponse
body, err := clusterapi.IndicesPayloads.VersionedObjectList.Marshal(vobjects)
if err != nil {
return nil, fmt.Errorf("encode request: %w", err)
}
req, err := newHttpReplicaRequest(
ctx, http.MethodPut, host, index, shard,
"", "_overwrite", bytes.NewReader(body))
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
err = c.do(c.timeoutUnit*90, req, body, &resp)
return resp, err
}
func (c *replicationClient) FetchObjects(ctx context.Context, host,
index, shard string, ids []strfmt.UUID,
) ([]objects.Replica, error) {
resp := make(objects.Replicas, len(ids))
idsBytes, err := json.Marshal(ids)
if err != nil {
return nil, fmt.Errorf("marshal ids: %w", err)
}
idsEncoded := base64.StdEncoding.EncodeToString(idsBytes)
req, err := newHttpReplicaRequest(ctx, http.MethodGet, host, index, shard, "", "", nil)
if err != nil {
return nil, fmt.Errorf("create http request: %w", err)
}
req.URL.RawQuery = url.Values{"ids": []string{idsEncoded}}.Encode()
err = c.doCustomUnmarshal(c.timeoutUnit*90, req, nil, resp.UnmarshalBinary)
return resp, err
}
func (c *replicationClient) PutObject(ctx context.Context, host, index,
shard, requestID string, obj *storobj.Object,
) (replica.SimpleResponse, error) {
var resp replica.SimpleResponse
body, err := clusterapi.IndicesPayloads.SingleObject.Marshal(obj)
if err != nil {
return resp, fmt.Errorf("encode request: %w", err)
}
req, err := newHttpReplicaRequest(ctx, http.MethodPost, host, index, shard, requestID, "", nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
clusterapi.IndicesPayloads.SingleObject.SetContentTypeHeaderReq(req)
err = c.do(c.timeoutUnit*90, req, body, &resp)
return resp, err
}
func (c *replicationClient) DeleteObject(ctx context.Context, host, index,
shard, requestID string, uuid strfmt.UUID,
) (replica.SimpleResponse, error) {
var resp replica.SimpleResponse
req, err := newHttpReplicaRequest(ctx, http.MethodDelete, host, index, shard, requestID, uuid.String(), nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
err = c.do(c.timeoutUnit*90, req, nil, &resp)
return resp, err
}
func (c *replicationClient) PutObjects(ctx context.Context, host, index,
shard, requestID string, objects []*storobj.Object,
) (replica.SimpleResponse, error) {
var resp replica.SimpleResponse
body, err := clusterapi.IndicesPayloads.ObjectList.Marshal(objects)
if err != nil {
return resp, fmt.Errorf("encode request: %w", err)
}
req, err := newHttpReplicaRequest(ctx, http.MethodPost, host, index, shard, requestID, "", nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
clusterapi.IndicesPayloads.ObjectList.SetContentTypeHeaderReq(req)
err = c.do(c.timeoutUnit*90, req, body, &resp)
return resp, err
}
func (c *replicationClient) MergeObject(ctx context.Context, host, index, shard, requestID string,
doc *objects.MergeDocument,
) (replica.SimpleResponse, error) {
var resp replica.SimpleResponse
body, err := clusterapi.IndicesPayloads.MergeDoc.Marshal(*doc)
if err != nil {
return resp, fmt.Errorf("encode request: %w", err)
}
req, err := newHttpReplicaRequest(ctx, http.MethodPatch, host, index, shard,
requestID, doc.ID.String(), nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
clusterapi.IndicesPayloads.MergeDoc.SetContentTypeHeaderReq(req)
err = c.do(c.timeoutUnit*90, req, body, &resp)
return resp, err
}
func (c *replicationClient) AddReferences(ctx context.Context, host, index,
shard, requestID string, refs []objects.BatchReference,
) (replica.SimpleResponse, error) {
var resp replica.SimpleResponse
body, err := clusterapi.IndicesPayloads.ReferenceList.Marshal(refs)
if err != nil {
return resp, fmt.Errorf("encode request: %w", err)
}
req, err := newHttpReplicaRequest(ctx, http.MethodPost, host, index, shard,
requestID, "references", nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
clusterapi.IndicesPayloads.ReferenceList.SetContentTypeHeaderReq(req)
err = c.do(c.timeoutUnit*90, req, body, &resp)
return resp, err
}
func (c *replicationClient) DeleteObjects(ctx context.Context, host, index, shard, requestID string,
uuids []strfmt.UUID, dryRun bool,
) (resp replica.SimpleResponse, err error) {
body, err := clusterapi.IndicesPayloads.BatchDeleteParams.Marshal(uuids, dryRun)
if err != nil {
return resp, fmt.Errorf("encode request: %w", err)
}
req, err := newHttpReplicaRequest(ctx, http.MethodDelete, host, index, shard, requestID, "", nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
clusterapi.IndicesPayloads.BatchDeleteParams.SetContentTypeHeaderReq(req)
err = c.do(c.timeoutUnit*90, req, body, &resp)
return resp, err
}
// Commit asks a host to commit and stores the response in the value pointed to by resp
func (c *replicationClient) Commit(ctx context.Context, host, index, shard string, requestID string, resp interface{}) error {
req, err := newHttpReplicaCMD(host, "commit", index, shard, requestID, nil)
if err != nil {
return fmt.Errorf("create http request: %w", err)
}
return c.do(c.timeoutUnit*90, req, nil, resp)
}
func (c *replicationClient) Abort(ctx context.Context, host, index, shard, requestID string) (
resp replica.SimpleResponse, err error,
) {
req, err := newHttpReplicaCMD(host, "abort", index, shard, requestID, nil)
if err != nil {
return resp, fmt.Errorf("create http request: %w", err)
}
err = c.do(c.timeoutUnit*5, req, nil, &resp)
return resp, err
}
func newHttpReplicaRequest(ctx context.Context, method, host, index, shard, requestId, suffix string, body io.Reader) (*http.Request, error) {
path := fmt.Sprintf("/replicas/indices/%s/shards/%s/objects", index, shard)
if suffix != "" {
path = fmt.Sprintf("%s/%s", path, suffix)
}
u := url.URL{
Scheme: "http",
Host: host,
Path: path,
}
if requestId != "" {
u.RawQuery = url.Values{replica.RequestKey: []string{requestId}}.Encode()
}
return http.NewRequestWithContext(ctx, method, u.String(), body)
}
func newHttpReplicaCMD(host, cmd, index, shard, requestId string, body io.Reader) (*http.Request, error) {
path := fmt.Sprintf("/replicas/indices/%s/shards/%s:%s", index, shard, cmd)
q := url.Values{replica.RequestKey: []string{requestId}}.Encode()
url := url.URL{Scheme: "http", Host: host, Path: path, RawQuery: q}
return http.NewRequest(http.MethodPost, url.String(), body)
}
func (c *replicationClient) do(timeout time.Duration, req *http.Request, body []byte, resp interface{}) (err error) {
ctx, cancel := context.WithTimeout(req.Context(), timeout)
defer cancel()
try := func(ctx context.Context) (bool, error) {
if body != nil {
req.Body = io.NopCloser(bytes.NewReader(body))
}
res, err := c.client.Do(req)
if err != nil {
return ctx.Err() == nil, fmt.Errorf("connect: %w", err)
}
defer res.Body.Close()
if code := res.StatusCode; code != http.StatusOK {
b, _ := io.ReadAll(res.Body)
return shouldRetry(code), fmt.Errorf("status code: %v, error: %s", code, b)
}
if err := json.NewDecoder(res.Body).Decode(resp); err != nil {
return false, fmt.Errorf("decode response: %w", err)
}
return false, nil
}
return c.retry(ctx, 9, try)
}
func (c *replicationClient) doCustomUnmarshal(timeout time.Duration,
req *http.Request, body []byte, decode func([]byte) error,
) (err error) {
return (*retryClient)(c).doWithCustomMarshaller(timeout, req, body, decode)
}
// backOff return a new random duration in the interval [d, 3d].
// It implements truncated exponential back-off with introduced jitter.
func backOff(d time.Duration) time.Duration {
return time.Duration(float64(d.Nanoseconds()*2) * (0.5 + rand.Float64()))
}
func shouldRetry(code int) bool {
return code == http.StatusInternalServerError ||
code == http.StatusTooManyRequests ||
code == http.StatusServiceUnavailable
}
|