Search code examples
gokuberneteskubernetes-pod

Weird behavior for executing a bpftrace shell command in Golang?


What do I want?

To parse the output of the command which basically runs inside a POD

Shell Command:

bpftrace -p 13111 -e uretprobe:/ebpfKit/Examples/cpp/main:enqueue { @[pid] = count(); interval:s:1{ print(@); clear(@); }

Code Used to parse:

func RunUretprobe(tool string, loguretprobe chan Log, pid string, filepath string, funcname string) {

            fmt.Println("checkpoint 1")
            command  := `uretprobe:` + filepath + `:` + funcname + `{ @[pid] = count(); }` +`interval:s:1` + `{ print(@); clear(@); }`
            cmd := exec.Command("bpftrace", "-p", pid , "-e", command)
            fmt.Println(cmd)
            stdout, err := cmd.StdoutPipe()
            if err != nil {
                    log.Fatal(err)
            }
            cmd.Start()
            buf := bufio.NewReader(stdout)
            fmt.Println("checkpoint 2")
            for {
    
                    line, _, _ := buf.ReadLine()
                    parsedLine := strings.Fields(string(line))
                    fmt.Println("checkpoint 3 -", cmd)
                    if (len(parsedLine) > 0) && parsedLine[0] != "Attaching"{
                            s := strings.Split(parsedLine[0], "[")
                            sep := strings.Split(s[1], "]")
                            log := sep[0] + " " + parsedLine[1]
                            timest := 0.00
                            fmt.Println("count--", log)
                            n := Log{Fulllog: log, Pid: 1234, Time: timest, Probe: tool}
                            loguretprobe <- n
    
                    }
            }
    }
    
    func main() {
    
    
    loguretprobe := make(chan Log, 1)
    
    go RunUretprobe("uretprobe", loguretprobe, "13111" , "/ebpfKit/Examples/cpp/main" , "enqueue")
    go func() {
    
            for val := range loguretprobe{
    
                    fmt.Println("Printing - ", val.Fulllog);
                    time.Sleep(time.Duration(1) * time.Second)
    
            }
    
    }()
    
    for{
            time.Sleep(time.Duration(1) * time.Second)
    }
    
    }

Problem:

When I manually enter the POD to run the above-written program, it works as required.

enter image description here

But, when I call RunUretprobe from another program through gRPC client, it gives me the following broken command(I got the logs using kubectl logs "pod_name") as shown:

enter image description here

Expectation:

To get a single command as shown in the first picture so that it gets executed and later on get parsed.


Solution

  • After string "/n" gets added, so I removed the newline using the following to make it work as expected:

    filepath = strings.Replace(filepath, "\n", "", -1)
    funcname = strings.Replace(funcname, "\n", "", -1)
    command  := `uretprobe:` + filepath + `:` + funcname + `{ @[pid] = count(); }` +`interval:s:1` + `{ print(@); clear(@); }`