github.com/fafucoder/cilium@v1.6.11/cilium/cmd/kvstore_get.go (about)

     1  // Copyright 2018-2019 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cmd
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  
    21  	"github.com/cilium/cilium/pkg/command"
    22  	"github.com/cilium/cilium/pkg/kvstore"
    23  
    24  	"github.com/spf13/cobra"
    25  )
    26  
    27  var kvstoreGetCmd = &cobra.Command{
    28  	Use:     "get [options] <key>",
    29  	Short:   "Retrieve a key",
    30  	Example: "cilium kvstore get --recursive foo",
    31  	Run: func(cmd *cobra.Command, args []string) {
    32  		key := ""
    33  
    34  		setupKvstore()
    35  
    36  		if len(args) > 0 {
    37  			key = args[0]
    38  		}
    39  
    40  		if recursive {
    41  			pairs, err := kvstore.Client().ListPrefix(key)
    42  			if err != nil {
    43  				Fatalf("Unable to list keys: %s", err)
    44  			}
    45  			if command.OutputJSON() {
    46  				if err := command.PrintOutput(pairs); err != nil {
    47  					os.Exit(1)
    48  				}
    49  				return
    50  			}
    51  			for k, v := range pairs {
    52  				fmt.Printf("%s => %s\n", k, string(v.Data))
    53  			}
    54  		} else {
    55  			val, err := kvstore.Client().Get(key)
    56  			if err != nil {
    57  				Fatalf("Unable to retrieve key: %s", err)
    58  			}
    59  			if command.OutputJSON() {
    60  				if err := command.PrintOutput(val); err != nil {
    61  					os.Exit(1)
    62  				}
    63  				return
    64  			}
    65  			fmt.Printf("%s => %s\n", key, string(val))
    66  		}
    67  	},
    68  }
    69  
    70  func init() {
    71  	kvstoreCmd.AddCommand(kvstoreGetCmd)
    72  	kvstoreGetCmd.Flags().BoolVar(&recursive, "recursive", false, "Recursive lookup")
    73  	command.AddJSONOutput(kvstoreGetCmd)
    74  }