github.com/zntrio/harp/v2@v2.0.9/pkg/kv/zookeeper/zookeeper.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package zookeeper
    19  
    20  import (
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"strings"
    25  
    26  	zk "github.com/go-zookeeper/zk"
    27  
    28  	"github.com/zntrio/harp/v2/pkg/kv"
    29  )
    30  
    31  type zkDriver struct {
    32  	client *zk.Conn
    33  }
    34  
    35  func Store(client *zk.Conn) kv.Store {
    36  	return &zkDriver{
    37  		client: client,
    38  	}
    39  }
    40  
    41  // -----------------------------------------------------------------------------
    42  
    43  func (d *zkDriver) Get(_ context.Context, key string) (*kv.Pair, error) {
    44  	// Retrieve from backend
    45  	item, meta, err := d.client.Get(d.normalize(key))
    46  	if err != nil {
    47  		if errors.Is(err, zk.ErrNoNode) {
    48  			return nil, kv.ErrKeyNotFound
    49  		}
    50  		return nil, fmt.Errorf("zk: unable to retrieve %q key: %w", key, err)
    51  	}
    52  
    53  	// No error
    54  	return &kv.Pair{
    55  		Key:     key,
    56  		Value:   item,
    57  		Version: uint64(meta.Version),
    58  	}, nil
    59  }
    60  
    61  func (d *zkDriver) Put(ctx context.Context, key string, value []byte) error {
    62  	// Check if key exists
    63  	exists, err := d.Exists(ctx, key)
    64  	if err != nil {
    65  		return err
    66  	}
    67  	if !exists {
    68  		// Create full hierarchy if the key doesn't exists
    69  		if errCreate := d.createFullPath(kv.SplitKey(strings.TrimSuffix(key, "/"))); errCreate != nil {
    70  			return fmt.Errorf("unable to create the complete path for key %q: %w", key, errCreate)
    71  		}
    72  	}
    73  
    74  	// Set the value (last version)
    75  	_, err = d.client.Set(d.normalize(key), value, -1)
    76  	if err != nil {
    77  		return fmt.Errorf("zk: unable to set %q value: %w", key, err)
    78  	}
    79  
    80  	// No error
    81  	return nil
    82  }
    83  
    84  func (d *zkDriver) Delete(_ context.Context, key string) error {
    85  	// Try to delete from store.
    86  	err := d.client.Delete(d.normalize(key), -1)
    87  	if err != nil {
    88  		if errors.Is(err, zk.ErrNoNode) {
    89  			return kv.ErrKeyNotFound
    90  		}
    91  		return fmt.Errorf("zk: unable to delete %q: %w", key, err)
    92  	}
    93  
    94  	// No error
    95  	return nil
    96  }
    97  
    98  func (d *zkDriver) Exists(_ context.Context, key string) (bool, error) {
    99  	key = d.normalize(key)
   100  
   101  	exists, _, err := d.client.Exists(key)
   102  	if err != nil {
   103  		return false, fmt.Errorf("zk: unable to check key %q existence: %w", key, err)
   104  	}
   105  
   106  	// No error
   107  	return exists, nil
   108  }
   109  
   110  func (d *zkDriver) List(ctx context.Context, basePath string) ([]*kv.Pair, error) {
   111  	// List keys from base path
   112  	keys, stat, err := d.client.Children(d.normalize(basePath))
   113  	if err != nil {
   114  		if errors.Is(err, zk.ErrNoNode) {
   115  			return nil, kv.ErrKeyNotFound
   116  		}
   117  		return nil, fmt.Errorf("zk: unable to list keys from %q: %w", basePath, err)
   118  	}
   119  
   120  	// Unpack values
   121  	results := []*kv.Pair{}
   122  	for _, key := range keys {
   123  		item, err := d.Get(ctx, strings.TrimSuffix(basePath, "/")+d.normalize(key))
   124  		if err != nil {
   125  			if errors.Is(err, kv.ErrKeyNotFound) {
   126  				return d.List(ctx, basePath)
   127  			}
   128  			return nil, err
   129  		}
   130  
   131  		results = append(results, &kv.Pair{
   132  			Key:     item.Key,
   133  			Value:   item.Value,
   134  			Version: uint64(stat.Version),
   135  		})
   136  	}
   137  
   138  	// No error
   139  	return results, nil
   140  }
   141  
   142  func (d *zkDriver) Close() error {
   143  	// Skip if client instance is nil
   144  	if d.client == nil {
   145  		return nil
   146  	}
   147  
   148  	// Close the client connection.
   149  	d.client.Close()
   150  
   151  	// No error
   152  	return nil
   153  }
   154  
   155  // -----------------------------------------------------------------------------
   156  
   157  // Normalize the key for usage in Consul.
   158  func (d *zkDriver) normalize(key string) string {
   159  	key = kv.Normalize(key)
   160  	return strings.TrimSuffix(key, "/")
   161  }
   162  
   163  // -----------------------------------------------------------------------------
   164  
   165  // createFullPath creates the entire path for a directory
   166  // that does not exist.
   167  func (d *zkDriver) createFullPath(path []string) error {
   168  	for i := 1; i <= len(path); i++ {
   169  		newpath := "/" + strings.Join(path[:i], "/")
   170  		_, err := d.client.Create(newpath, []byte{}, 0, zk.WorldACL(zk.PermAll))
   171  		if err != nil {
   172  			// Skip if node already exists
   173  			if !errors.Is(err, zk.ErrNodeExists) {
   174  				return err
   175  			}
   176  		}
   177  	}
   178  	return nil
   179  }