vitess.io/vitess@v0.16.2/go/vt/topo/zk2topo/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 zk2topo
    18  
    19  import (
    20  	"path"
    21  	"sort"
    22  	"sync"
    23  
    24  	"context"
    25  
    26  	"vitess.io/vitess/go/vt/topo"
    27  )
    28  
    29  // ListDir is part of the topo.Conn interface.
    30  func (zs *Server) ListDir(ctx context.Context, dirPath string, full bool) ([]topo.DirEntry, error) {
    31  	zkPath := path.Join(zs.root, dirPath)
    32  
    33  	isRoot := false
    34  	if dirPath == "" || dirPath == "/" {
    35  		isRoot = true
    36  	}
    37  
    38  	children, _, err := zs.conn.Children(ctx, zkPath)
    39  	if err != nil {
    40  		return nil, convertError(err, zkPath)
    41  	}
    42  	sort.Strings(children)
    43  
    44  	result := make([]topo.DirEntry, len(children))
    45  	for i, child := range children {
    46  		result[i].Name = child
    47  	}
    48  
    49  	if full {
    50  		var wg sync.WaitGroup
    51  		for i := range result {
    52  			if isRoot && result[i].Name == electionsPath {
    53  				// Shortcut here: we know it's an ephemeral directory.
    54  				result[i].Type = topo.TypeDirectory
    55  				result[i].Ephemeral = true
    56  				continue
    57  			}
    58  
    59  			wg.Add(1)
    60  			go func(i int) {
    61  				defer wg.Done()
    62  				p := path.Join(zkPath, result[i].Name)
    63  				_, stat, err := zs.conn.Get(ctx, p)
    64  				if err != nil {
    65  					return
    66  				}
    67  				if stat.NumChildren == 0 {
    68  					result[i].Type = topo.TypeFile
    69  				} else {
    70  					result[i].Type = topo.TypeDirectory
    71  				}
    72  				if stat.EphemeralOwner != 0 {
    73  					// This is an ephemeral node, we use this for locks.
    74  					result[i].Ephemeral = true
    75  				}
    76  			}(i)
    77  		}
    78  		wg.Wait()
    79  	}
    80  
    81  	return result, nil
    82  }