github.com/looshlee/cilium@v1.6.12/test/bpf/perf-event-test.go (about)

     1  // Copyright 2016-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 main
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  
    21  	"github.com/cilium/cilium/pkg/bpf"
    22  
    23  	"github.com/spf13/cobra"
    24  )
    25  
    26  var (
    27  	config = bpf.PerfEventConfig{
    28  		MapName:      "perf_test_events",
    29  		Type:         bpf.PERF_TYPE_SOFTWARE,
    30  		Config:       bpf.PERF_COUNT_SW_BPF_OUTPUT,
    31  		SampleType:   bpf.PERF_SAMPLE_RAW,
    32  		WakeupEvents: 1,
    33  	}
    34  )
    35  
    36  func receiveEvent(msg *bpf.PerfEventSample, cpu int) {
    37  	fmt.Printf("%+v\n", msg)
    38  }
    39  
    40  func lostEvent(lost *bpf.PerfEventLost, cpu int) {
    41  	fmt.Printf("Lost %d\n", lost.Lost)
    42  }
    43  
    44  func errEvent(err *bpf.PerfEvent) {
    45  	fmt.Printf("Error\n")
    46  }
    47  
    48  var RootCmd = &cobra.Command{
    49  	Use:   "perf-event-test",
    50  	Short: "Test utility for perf events",
    51  	Run: func(cmd *cobra.Command, args []string) {
    52  		events, err := bpf.NewPerCpuEvents(&config)
    53  		if err != nil {
    54  			panic(err)
    55  		}
    56  
    57  		for {
    58  			todo, err := events.Poll(-1)
    59  			if err != nil {
    60  				panic(err)
    61  			}
    62  			if todo > 0 {
    63  				events.ReadAll(receiveEvent, lostEvent, errEvent)
    64  			}
    65  		}
    66  
    67  	},
    68  }
    69  
    70  func main() {
    71  	if err := RootCmd.Execute(); err != nil {
    72  		fmt.Fprintf(os.Stderr, "%s", err)
    73  		os.Exit(-1)
    74  	}
    75  }
    76  
    77  func init() {
    78  	flags := RootCmd.PersistentFlags()
    79  	flags.IntVarP(&config.NumCpus, "num-cpus", "c", 1, "Number of CPUs")
    80  	flags.IntVarP(&config.NumPages, "num-pagse", "n", 8, "Number of pages for ring buffer")
    81  }