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

     1  // Copyright 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/common"
    22  	"github.com/cilium/cilium/pkg/command"
    23  	"github.com/cilium/cilium/pkg/maps/nat"
    24  
    25  	"github.com/spf13/cobra"
    26  )
    27  
    28  // bpfNatListCmd represents the bpf_nat_list command
    29  var bpfNatListCmd = &cobra.Command{
    30  	Use:     "list",
    31  	Aliases: []string{"ls"},
    32  	Short:   "List all NAT mapping entries",
    33  	Run: func(cmd *cobra.Command, args []string) {
    34  		common.RequireRootPrivilege("cilium bpf nat list")
    35  		dumpNat()
    36  	},
    37  }
    38  
    39  func init() {
    40  	bpfNatCmd.AddCommand(bpfNatListCmd)
    41  	command.AddJSONOutput(bpfNatListCmd)
    42  }
    43  
    44  func dumpNat() {
    45  	ipv4, ipv6 := nat.GlobalMaps(true, true)
    46  
    47  	for _, m := range []*nat.Map{ipv4, ipv6} {
    48  		if m == nil {
    49  			continue
    50  		}
    51  		path, err := m.Path()
    52  		if err == nil {
    53  			err = m.Open()
    54  		}
    55  		if err != nil {
    56  			if os.IsNotExist(err) {
    57  				fmt.Fprintf(os.Stderr, "Unable to open %s: %s. Skipping.\n", path, err)
    58  				continue
    59  			}
    60  			Fatalf("Unable to open %s: %s", path, err)
    61  		}
    62  		defer m.Close()
    63  		if command.OutputJSON() {
    64  			if err := command.PrintOutput(m); err != nil {
    65  				os.Exit(1)
    66  			}
    67  		} else {
    68  			out, err := m.DumpEntries()
    69  			if err != nil {
    70  				Fatalf("Error while dumping BPF Map: %s", err)
    71  			}
    72  			fmt.Println(out)
    73  		}
    74  	}
    75  }