vitess.io/vitess@v0.16.2/go/vt/topo/consultopo/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 consultopo
    18  
    19  import (
    20  	"path"
    21  	"strings"
    22  
    23  	"context"
    24  
    25  	"vitess.io/vitess/go/vt/topo"
    26  )
    27  
    28  // ListDir is part of the topo.Conn interface.
    29  func (s *Server) ListDir(ctx context.Context, dirPath string, full bool) ([]topo.DirEntry, error) {
    30  	nodePath := path.Join(s.root, dirPath) + "/"
    31  	if nodePath == "//" {
    32  		// Special case where c.root is "/", dirPath is empty,
    33  		// we would end up with "//". in that case, we want "/".
    34  		nodePath = "/"
    35  	}
    36  
    37  	isRoot := false
    38  	if dirPath == "" || dirPath == "/" {
    39  		isRoot = true
    40  	}
    41  
    42  	keys, _, err := s.kv.Keys(nodePath, "", nil)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	if len(keys) == 0 {
    47  		// No key starts with this prefix, means the directory
    48  		// doesn't exist.
    49  		return nil, topo.NewError(topo.NoNode, nodePath)
    50  	}
    51  
    52  	prefixLen := len(nodePath)
    53  	var result []topo.DirEntry
    54  	for _, p := range keys {
    55  		// Remove the prefix, base path.
    56  		if !strings.HasPrefix(p, nodePath) {
    57  			return nil, ErrBadResponse
    58  		}
    59  		p = p[prefixLen:]
    60  
    61  		// Keep only the part until the first '/'.
    62  		t := topo.TypeFile
    63  		if i := strings.Index(p, "/"); i >= 0 {
    64  			p = p[:i]
    65  			t = topo.TypeDirectory
    66  		}
    67  
    68  		// Remove duplicates, add to list.
    69  		if len(result) == 0 || result[len(result)-1].Name != p {
    70  			e := topo.DirEntry{
    71  				Name: p,
    72  			}
    73  			if full {
    74  				e.Type = t
    75  				if isRoot && p == electionsPath {
    76  					e.Ephemeral = true
    77  				}
    78  				if p == locksFilename && t == topo.TypeFile {
    79  					// A file called 'Lock' is always ephemeral.
    80  					// (A directory called 'Lock' could be a keyspace or
    81  					// a shard named Lock).
    82  					e.Ephemeral = true
    83  				}
    84  			}
    85  			result = append(result, e)
    86  		}
    87  	}
    88  
    89  	return result, nil
    90  }