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
| type EtcdStore struct { sync.RWMutex prefix string rawClient *clientv3.Client kv clientv3.KV }
func (e *EtcdStore) ConnectEtcd(addr string) (err error) { config := clientv3.Config{ Endpoints: []string{addr}, DialTimeout: time.Second * 2, } e.rawClient, err = clientv3.New(config) if err != nil { return err }
e.kv = clientv3.NewKV(e.rawClient)
return nil }
func (e *EtcdStore) SetPrefixPath(path string) { e.prefix = path }
func (e *EtcdStore) BackupTo(to string) (err error) { e.Lock() defer e.Unlock()
targetEtcdClient, err := clientv3.New(clientv3.Config{ Endpoints: []string{to}, DialTimeout: time.Second * 2, }) if err != nil { return err }
defer targetEtcdClient.Close() kv := clientv3.NewKV(targetEtcdClient)
getResp, err := e.kv.Get(context.TODO(), e.prefix, clientv3.WithPrefix()) if err != nil { return }
for _, kvpair := range getResp.Kvs { fmt.Println(string(kvpair.Key), string(kvpair.Value)) putOp := clientv3.OpPut(string(kvpair.Key), string(kvpair.Value)) opResp, err := kv.Do(context.TODO(), putOp) if err != nil { fmt.Println(err, opResp.Put().Header.Revision) return err } }
return nil }
func ExtractPrefix(regKey, prefix string) string { return strings.TrimPrefix(regKey, prefix) }
func (e *EtcdStore) BackupToSpecifyDir(toAddr, newPrefix string) (err error) { e.Lock() defer e.Unlock()
targetEtcdClient, err := clientv3.New(clientv3.Config{ Endpoints: []string{toAddr}, DialTimeout: time.Second * 2, }) if err != nil { return err }
defer targetEtcdClient.Close() kv := clientv3.NewKV(targetEtcdClient)
getResp, err := e.kv.Get(context.TODO(), e.prefix, clientv3.WithPrefix()) if err != nil { return }
for _, kvpair := range getResp.Kvs { fmt.Println(string(kvpair.Key), string(kvpair.Value))
newEtcdPath := path.Join(newPrefix, ExtractPrefix(string(kvpair.Key), e.prefix))
putOp := clientv3.OpPut(newEtcdPath, string(kvpair.Value)) opResp, err := kv.Do(context.TODO(), putOp) if err != nil { fmt.Println(err, opResp.Put().Header.Revision) return err } }
return nil }
|