github.com/looshlee/beatles@v0.0.0-20220727174639-742810ab631c/pkg/kvstore/client.go (about) 1 // Copyright 2016-2019 Authors of Cilium 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 kvstore 16 17 import ( 18 "fmt" 19 ) 20 21 var ( 22 // defaultClient is the default client initialized by initClient 23 defaultClient BackendOperations 24 // defaultClientSet is a channel that is closed whenever the defaultClient 25 // is set. 26 defaultClientSet = make(chan struct{}) 27 ) 28 29 func initClient(module backendModule, opts *ExtraOptions) error { 30 scopedLog := log.WithField(fieldKVStoreModule, module.getName()) 31 c, errChan := module.newClient(opts) 32 if c == nil { 33 err := <-errChan 34 scopedLog.WithError(err).Fatal("Unable to create kvstore client") 35 } 36 37 defaultClient = c 38 select { 39 case <-defaultClientSet: 40 // avoid closing channel already closed. 41 default: 42 close(defaultClientSet) 43 } 44 45 go func() { 46 err, isErr := <-errChan 47 if isErr && err != nil { 48 scopedLog.WithError(err).Fatal("Unable to connect to kvstore") 49 } 50 deleteLegacyPrefixes() 51 }() 52 53 return nil 54 } 55 56 // Client returns the global kvstore client or nil if the client is not configured yet 57 func Client() BackendOperations { 58 <-defaultClientSet 59 return defaultClient 60 } 61 62 // NewClient returns a new kvstore client based on the configuration 63 func NewClient(selectedBackend string, opts map[string]string, options *ExtraOptions) (BackendOperations, chan error) { 64 // Channel used to report immediate errors, module.newClient will 65 // create and return a different channel, caller doesn't need to know 66 errChan := make(chan error, 1) 67 defer close(errChan) 68 69 module := getBackend(selectedBackend) 70 if module == nil { 71 errChan <- fmt.Errorf("unknown key-value store type %q. See cilium.link/err-kvstore for details", selectedBackend) 72 return nil, errChan 73 } 74 75 if err := module.setConfig(opts); err != nil { 76 errChan <- err 77 return nil, errChan 78 } 79 80 if err := module.setExtraConfig(options); err != nil { 81 errChan <- err 82 return nil, errChan 83 } 84 85 return module.newClient(options) 86 }