vitess.io/vitess@v0.16.2/go/vt/topo/etcd2topo/directory.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package etcd2topo 18 19 import ( 20 "path" 21 "strings" 22 23 "context" 24 25 clientv3 "go.etcd.io/etcd/client/v3" 26 27 "vitess.io/vitess/go/vt/topo" 28 ) 29 30 // ListDir is part of the topo.Conn interface. 31 func (s *Server) ListDir(ctx context.Context, dirPath string, full bool) ([]topo.DirEntry, error) { 32 nodePath := path.Join(s.root, dirPath) + "/" 33 if nodePath == "//" { 34 // Special case where s.root is "/", dirPath is empty, 35 // we would end up with "//". in that case, we want "/". 36 nodePath = "/" 37 } 38 resp, err := s.cli.Get(ctx, nodePath, 39 clientv3.WithPrefix(), 40 clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend), 41 clientv3.WithKeysOnly()) 42 if err != nil { 43 return nil, convertError(err, dirPath) 44 } 45 if len(resp.Kvs) == 0 { 46 // No key starts with this prefix, means the directory 47 // doesn't exist. 48 return nil, topo.NewError(topo.NoNode, nodePath) 49 } 50 51 prefixLen := len(nodePath) 52 var result []topo.DirEntry 53 for _, ev := range resp.Kvs { 54 p := string(ev.Key) 55 56 // Remove the prefix, base path. 57 if !strings.HasPrefix(p, nodePath) { 58 return nil, ErrBadResponse 59 } 60 p = p[prefixLen:] 61 62 // Keep only the part until the first '/'. 63 t := topo.TypeFile 64 if i := strings.Index(p, "/"); i >= 0 { 65 p = p[:i] 66 t = topo.TypeDirectory 67 } 68 69 // Remove duplicates, add to list. 70 if len(result) == 0 || result[len(result)-1].Name != p { 71 e := topo.DirEntry{ 72 Name: p, 73 } 74 if full { 75 e.Type = t 76 if ev.Lease != 0 { 77 // Only locks have a lease associated with them. 78 e.Ephemeral = true 79 } 80 } 81 result = append(result, e) 82 } 83 } 84 85 return result, nil 86 }