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

     1  // Copyright 2018 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  	"text/tabwriter"
    21  
    22  	daemonAPI "github.com/cilium/cilium/api/v1/client/daemon"
    23  	"github.com/cilium/cilium/api/v1/models"
    24  	"github.com/cilium/cilium/pkg/api"
    25  	"github.com/cilium/cilium/pkg/command"
    26  
    27  	"github.com/spf13/cobra"
    28  )
    29  
    30  // mapGetCmd represents the map_get command
    31  var mapGetCmd = &cobra.Command{
    32  	Use:     "get <name>",
    33  	Short:   "Display BPF map information",
    34  	Example: "cilium map get cilium_ipcache",
    35  	Run: func(cmd *cobra.Command, args []string) {
    36  		if len(args) == 0 {
    37  			Fatalf("map name must be specified")
    38  		}
    39  
    40  		params := daemonAPI.NewGetMapNameParams().WithName(args[0]).WithTimeout(api.ClientTimeout)
    41  
    42  		resp, err := client.Daemon.GetMapName(params)
    43  		if err != nil {
    44  			Fatalf("%s", err)
    45  		}
    46  
    47  		m := resp.Payload
    48  		if m == nil {
    49  			return
    50  		}
    51  
    52  		if command.OutputJSON() {
    53  			if err := command.PrintOutput(m); err != nil {
    54  				os.Exit(1)
    55  			}
    56  		} else {
    57  			printMapEntries(m)
    58  		}
    59  	},
    60  }
    61  
    62  func printMapEntries(m *models.BPFMap) {
    63  	if m.Cache == nil {
    64  		fmt.Printf("Cache is disabled\n\n")
    65  		return
    66  	}
    67  
    68  	if len(m.Cache) == 0 {
    69  		fmt.Printf("Cache is empty\n\n")
    70  		return
    71  	}
    72  
    73  	w := tabwriter.NewWriter(os.Stdout, 5, 0, 3, ' ', 0)
    74  	fmt.Fprintf(w, "Key\tValue\tState\tError\n")
    75  	for _, e := range m.Cache {
    76  		if e != nil {
    77  			fmt.Fprintf(w, "%s\t%s\t%s\t%s\n",
    78  				e.Key, e.Value, e.DesiredAction, e.LastError)
    79  		}
    80  	}
    81  	w.Flush()
    82  }
    83  
    84  func init() {
    85  	mapCmd.AddCommand(mapGetCmd)
    86  	command.AddJSONOutput(mapGetCmd)
    87  }