...

Source file src/go.etcd.io/etcd/server/v3/etcdserver/api/membership/confstate.go

Documentation: go.etcd.io/etcd/server/v3/etcdserver/api/membership

     1  // Copyright 2021 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 membership
    16  
    17  import (
    18  	"encoding/json"
    19  	"log"
    20  
    21  	"go.etcd.io/etcd/raft/v3/raftpb"
    22  	"go.etcd.io/etcd/server/v3/mvcc/backend"
    23  	"go.etcd.io/etcd/server/v3/mvcc/buckets"
    24  	"go.uber.org/zap"
    25  )
    26  
    27  var (
    28  	confStateKey = []byte("confState")
    29  )
    30  
    31  // MustUnsafeSaveConfStateToBackend persists confState using given transaction (tx).
    32  // confState in backend is persisted since etcd v3.5.
    33  func MustUnsafeSaveConfStateToBackend(lg *zap.Logger, tx backend.BatchTx, confState *raftpb.ConfState) {
    34  	confStateBytes, err := json.Marshal(confState)
    35  	if err != nil {
    36  		lg.Panic("Cannot marshal raftpb.ConfState", zap.Stringer("conf-state", confState), zap.Error(err))
    37  	}
    38  
    39  	tx.UnsafePut(buckets.Meta, confStateKey, confStateBytes)
    40  }
    41  
    42  // UnsafeConfStateFromBackend retrieves ConfState from the backend.
    43  // Returns nil if confState in backend is not persisted (e.g. backend writen by <v3.5).
    44  func UnsafeConfStateFromBackend(lg *zap.Logger, tx backend.ReadTx) *raftpb.ConfState {
    45  	keys, vals := tx.UnsafeRange(buckets.Meta, confStateKey, nil, 0)
    46  	if len(keys) == 0 {
    47  		return nil
    48  	}
    49  
    50  	if len(keys) != 1 {
    51  		lg.Panic(
    52  			"unexpected number of key: "+string(confStateKey)+" when getting cluster version from backend",
    53  			zap.Int("number-of-key", len(keys)),
    54  		)
    55  	}
    56  	var confState raftpb.ConfState
    57  	if err := json.Unmarshal(vals[0], &confState); err != nil {
    58  		log.Panic("Cannot unmarshal confState json retrieved from the backend",
    59  			zap.ByteString("conf-state-json", vals[0]),
    60  			zap.Error(err))
    61  	}
    62  	return &confState
    63  }
    64  

View as plain text