k3s/pkg/tools/fake_etcd_client.go

284 lines
7.3 KiB
Go
Raw Normal View History

2014-06-06 23:40:48 +00:00
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2014-06-23 18:32:11 +00:00
package tools
2014-06-06 23:40:48 +00:00
import (
"errors"
2014-06-06 23:40:48 +00:00
"fmt"
"sync"
2014-06-06 23:40:48 +00:00
"github.com/coreos/go-etcd/etcd"
)
type EtcdResponseWithError struct {
R *etcd.Response
E error
// if N is non-null, it will be assigned into the map after this response is used for an operation
N *EtcdResponseWithError
2014-06-06 23:40:48 +00:00
}
// TestLogger is a type passed to Test functions to support formatted test logs.
type TestLogger interface {
Errorf(format string, args ...interface{})
Logf(format string, args ...interface{})
}
2014-06-06 23:40:48 +00:00
type FakeEtcdClient struct {
2014-07-03 00:30:56 +00:00
watchCompletedChan chan bool
2014-06-30 21:48:57 +00:00
Data map[string]EtcdResponseWithError
DeletedKeys []string
expectNotFoundGetSet map[string]struct{}
sync.Mutex
Err error
t TestLogger
Ix int
TestIndex bool
ChangeIndex uint64
2014-09-24 00:47:05 +00:00
LastSetTTL uint64
// Will become valid after Watch is called; tester may write to it. Tester may
// also read from it to verify that it's closed after injecting an error.
WatchResponse chan *etcd.Response
WatchIndex uint64
// Write to this to prematurely stop a Watch that is running in a goroutine.
WatchInjectError chan<- error
WatchStop chan<- bool
// If non-nil, will be returned immediately when Watch is called.
WatchImmediateError error
2014-06-06 23:40:48 +00:00
}
func NewFakeEtcdClient(t TestLogger) *FakeEtcdClient {
2014-06-30 22:32:55 +00:00
ret := &FakeEtcdClient{
t: t,
expectNotFoundGetSet: map[string]struct{}{},
Data: map[string]EtcdResponseWithError{},
2014-06-06 23:40:48 +00:00
}
2014-07-01 18:21:17 +00:00
// There are three publicly accessible channels in FakeEtcdClient:
// - WatchResponse
// - WatchInjectError
// - WatchStop
// They are only available when Watch() is called. If users of
// FakeEtcdClient want to use any of these channels, they have to call
// WaitForWatchCompletion before any operation on these channels.
2014-07-03 00:30:56 +00:00
// Internally, FakeEtcdClient use watchCompletedChan to indicate if the
2014-07-01 18:21:17 +00:00
// Watch() method has been called. WaitForWatchCompletion() will wait
2014-07-03 00:30:56 +00:00
// on this channel. WaitForWatchCompletion() will return only when
// WatchResponse, WatchInjectError and WatchStop are ready to read/write.
ret.watchCompletedChan = make(chan bool)
2014-06-30 22:32:55 +00:00
return ret
2014-06-06 23:40:48 +00:00
}
func (f *FakeEtcdClient) ExpectNotFoundGet(key string) {
f.expectNotFoundGetSet[key] = struct{}{}
}
2014-07-30 10:31:35 +00:00
func (f *FakeEtcdClient) generateIndex() uint64 {
if !f.TestIndex {
return 0
}
2014-07-30 10:31:35 +00:00
f.ChangeIndex++
f.t.Logf("generating index %v", f.ChangeIndex)
2014-07-30 10:31:35 +00:00
return f.ChangeIndex
}
// Requires that f.Mutex be held.
func (f *FakeEtcdClient) updateResponse(key string) {
resp, found := f.Data[key]
if !found || resp.N == nil {
return
}
f.Data[key] = *resp.N
}
2014-06-06 23:40:48 +00:00
func (f *FakeEtcdClient) AddChild(key, data string, ttl uint64) (*etcd.Response, error) {
f.Mutex.Lock()
defer f.Mutex.Unlock()
f.Ix = f.Ix + 1
return f.setLocked(fmt.Sprintf("%s/%d", key, f.Ix), data, ttl)
2014-06-06 23:40:48 +00:00
}
func (f *FakeEtcdClient) Get(key string, sort, recursive bool) (*etcd.Response, error) {
f.Mutex.Lock()
defer f.Mutex.Unlock()
defer f.updateResponse(key)
2014-06-06 23:40:48 +00:00
result := f.Data[key]
if result.R == nil {
if _, ok := f.expectNotFoundGetSet[key]; !ok {
f.t.Errorf("Unexpected get for %s", key)
}
return &etcd.Response{}, EtcdErrorNotFound
2014-06-06 23:40:48 +00:00
}
2014-06-27 19:54:45 +00:00
f.t.Logf("returning %v: %v %#v", key, result.R, result.E)
2014-06-06 23:40:48 +00:00
return result.R, result.E
}
func (f *FakeEtcdClient) nodeExists(key string) bool {
result, ok := f.Data[key]
return ok && result.R != nil && result.R.Node != nil && result.E == nil
}
func (f *FakeEtcdClient) setLocked(key, value string, ttl uint64) (*etcd.Response, error) {
2014-09-24 00:47:05 +00:00
f.LastSetTTL = ttl
2014-07-31 07:15:03 +00:00
if f.Err != nil {
return nil, f.Err
}
2014-07-30 10:31:35 +00:00
i := f.generateIndex()
if f.nodeExists(key) {
prevResult := f.Data[key]
2014-07-30 10:31:35 +00:00
createdIndex := prevResult.R.Node.CreatedIndex
f.t.Logf("updating %v, index %v -> %v", key, createdIndex, i)
2014-07-30 10:31:35 +00:00
result := EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Value: value,
CreatedIndex: createdIndex,
ModifiedIndex: i,
},
},
}
f.Data[key] = result
2014-07-31 07:15:03 +00:00
return result.R, nil
2014-07-30 10:31:35 +00:00
}
f.t.Logf("creating %v, index %v", key, i)
2014-06-06 23:40:48 +00:00
result := EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
2014-07-30 10:31:35 +00:00
Value: value,
CreatedIndex: i,
ModifiedIndex: i,
TTL: int64(ttl),
2014-06-06 23:40:48 +00:00
},
},
}
f.Data[key] = result
2014-07-31 07:15:03 +00:00
return result.R, nil
2014-06-06 23:40:48 +00:00
}
func (f *FakeEtcdClient) Set(key, value string, ttl uint64) (*etcd.Response, error) {
f.Mutex.Lock()
defer f.Mutex.Unlock()
defer f.updateResponse(key)
return f.setLocked(key, value, ttl)
}
func (f *FakeEtcdClient) CompareAndSwap(key, value string, ttl uint64, prevValue string, prevIndex uint64) (*etcd.Response, error) {
if f.Err != nil {
f.t.Logf("c&s: returning err %v", f.Err)
return nil, f.Err
}
if !f.TestIndex {
f.t.Errorf("Enable TestIndex for test involving CompareAndSwap")
return nil, errors.New("Enable TestIndex for test involving CompareAndSwap")
}
if prevValue == "" && prevIndex == 0 {
return nil, errors.New("Either prevValue or prevIndex must be specified.")
}
f.Mutex.Lock()
defer f.Mutex.Unlock()
defer f.updateResponse(key)
if !f.nodeExists(key) {
f.t.Logf("c&s: node doesn't exist")
return nil, EtcdErrorNotFound
}
prevNode := f.Data[key].R.Node
if prevValue != "" && prevValue != prevNode.Value {
f.t.Logf("body didn't match")
return nil, EtcdErrorTestFailed
}
if prevIndex != 0 && prevIndex != prevNode.ModifiedIndex {
f.t.Logf("got index %v but needed %v", prevIndex, prevNode.ModifiedIndex)
return nil, EtcdErrorTestFailed
}
return f.setLocked(key, value, ttl)
}
2014-06-06 23:40:48 +00:00
func (f *FakeEtcdClient) Create(key, value string, ttl uint64) (*etcd.Response, error) {
f.Mutex.Lock()
defer f.Mutex.Unlock()
defer f.updateResponse(key)
if f.nodeExists(key) {
return nil, EtcdErrorNodeExist
}
return f.setLocked(key, value, ttl)
2014-06-06 23:40:48 +00:00
}
2014-06-06 23:40:48 +00:00
func (f *FakeEtcdClient) Delete(key string, recursive bool) (*etcd.Response, error) {
2014-07-31 07:15:03 +00:00
if f.Err != nil {
return nil, f.Err
2014-07-31 07:15:03 +00:00
}
2014-06-27 19:54:45 +00:00
f.Data[key] = EtcdResponseWithError{
R: &etcd.Response{
Node: nil,
},
E: EtcdErrorNotFound,
2014-06-27 19:54:45 +00:00
}
f.DeletedKeys = append(f.DeletedKeys, key)
2014-07-31 07:15:03 +00:00
return &etcd.Response{}, nil
2014-06-06 23:40:48 +00:00
}
func (f *FakeEtcdClient) WaitForWatchCompletion() {
2014-07-03 00:30:56 +00:00
<-f.watchCompletedChan
2014-06-30 21:48:57 +00:00
}
2014-06-06 23:40:48 +00:00
func (f *FakeEtcdClient) Watch(prefix string, waitIndex uint64, recursive bool, receiver chan *etcd.Response, stop chan bool) (*etcd.Response, error) {
if f.WatchImmediateError != nil {
return nil, f.WatchImmediateError
}
f.WatchResponse = receiver
f.WatchStop = stop
f.WatchIndex = waitIndex
injectedError := make(chan error)
2014-06-30 21:48:57 +00:00
defer close(injectedError)
f.WatchInjectError = injectedError
2014-06-30 23:07:46 +00:00
if receiver == nil {
return f.Get(prefix, false, recursive)
} else {
// Emulate etcd's behavior. (I think.)
defer close(receiver)
}
2014-07-03 00:30:56 +00:00
f.watchCompletedChan <- true
select {
case <-stop:
return nil, etcd.ErrWatchStoppedByUser
case err := <-injectedError:
return nil, err
}
2014-06-06 23:40:48 +00:00
}