David K. Bainbridge | e05cf0c | 2021-08-19 03:16:50 +0000 | [diff] [blame^] | 1 | // Copyright 2020 The etcd Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package clientv3 |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "strings" |
| 20 | |
| 21 | "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes" |
| 22 | "github.com/coreos/etcd/version" |
| 23 | "google.golang.org/grpc/metadata" |
| 24 | ) |
| 25 | |
| 26 | // WithRequireLeader requires client requests to only succeed |
| 27 | // when the cluster has a leader. |
| 28 | func WithRequireLeader(ctx context.Context) context.Context { |
| 29 | md, ok := metadata.FromOutgoingContext(ctx) |
| 30 | if !ok { // no outgoing metadata ctx key, create one |
| 31 | md = metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader) |
| 32 | return metadata.NewOutgoingContext(ctx, md) |
| 33 | } |
| 34 | copied := md.Copy() // avoid racey updates |
| 35 | // overwrite/add 'hasleader' key/value |
| 36 | metadataSet(copied, rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader) |
| 37 | return metadata.NewOutgoingContext(ctx, copied) |
| 38 | } |
| 39 | |
| 40 | // embeds client version |
| 41 | func withVersion(ctx context.Context) context.Context { |
| 42 | md, ok := metadata.FromOutgoingContext(ctx) |
| 43 | if !ok { // no outgoing metadata ctx key, create one |
| 44 | md = metadata.Pairs(rpctypes.MetadataClientAPIVersionKey, version.APIVersion) |
| 45 | return metadata.NewOutgoingContext(ctx, md) |
| 46 | } |
| 47 | copied := md.Copy() // avoid racey updates |
| 48 | // overwrite/add version key/value |
| 49 | metadataSet(copied, rpctypes.MetadataClientAPIVersionKey, version.APIVersion) |
| 50 | return metadata.NewOutgoingContext(ctx, copied) |
| 51 | } |
| 52 | |
| 53 | func metadataGet(md metadata.MD, k string) []string { |
| 54 | k = strings.ToLower(k) |
| 55 | return md[k] |
| 56 | } |
| 57 | |
| 58 | func metadataSet(md metadata.MD, k string, vals ...string) { |
| 59 | if len(vals) == 0 { |
| 60 | return |
| 61 | } |
| 62 | k = strings.ToLower(k) |
| 63 | md[k] = vals |
| 64 | } |