github.com/fafucoder/cilium@v1.6.11/cilium/cmd/bpf_sha_get.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  	"encoding/base64"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"path/filepath"
    22  	"regexp"
    23  	"strings"
    24  
    25  	"github.com/cilium/cilium/common"
    26  	"github.com/cilium/cilium/pkg/command"
    27  
    28  	"github.com/spf13/cobra"
    29  )
    30  
    31  var bpfShaGetCmd = &cobra.Command{
    32  	Use:     "get <sha>",
    33  	Aliases: []string{"describe"},
    34  	Short:   "Get datapath SHA header",
    35  	Run: func(cmd *cobra.Command, args []string) {
    36  		common.RequireRootPrivilege("cilium bpf sha get")
    37  		if len(args) == 0 {
    38  			cmd.Help()
    39  		} else {
    40  			dumpSha(args[0])
    41  		}
    42  	},
    43  }
    44  
    45  func init() {
    46  	bpfTemplateCmd.AddCommand(bpfShaGetCmd)
    47  	command.AddJSONOutput(bpfShaGetCmd)
    48  }
    49  
    50  func dumpSha(sha string) {
    51  	headerPath := filepath.Join(templatesDir, sha, common.CHeaderFileName)
    52  	text, err := ioutil.ReadFile(headerPath)
    53  	if err != nil {
    54  		Fatalf("Failed to describe SHA: %s", err)
    55  	}
    56  
    57  	if command.OutputJSON() {
    58  		regex, err := regexp.Compile("// JSON_OUTPUT: (?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)")
    59  		if err != nil {
    60  			Fatalf("Error preparing regex for parsing JSON: %s\n", err)
    61  		}
    62  
    63  		jsonEncStr := regex.FindString(fmt.Sprintf("%s", text))
    64  		if jsonEncStr == "" {
    65  			Fatalf("No JSON embedded in the file.")
    66  		}
    67  
    68  		jsonStr, err := base64.StdEncoding.DecodeString(strings.Replace(jsonEncStr, "// JSON_OUTPUT: ", "", -1))
    69  		if err != nil {
    70  			Fatalf("Error while decoding JSON encoded as base64 string: %s", err)
    71  		}
    72  
    73  		if err := command.PrintOutput(jsonStr); err != nil {
    74  			Fatalf("error printing output in JSON: %s\n", err)
    75  		}
    76  		return
    77  	}
    78  
    79  	fmt.Printf("%s", text)
    80  }