github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/controller/pkg/dmesgparser/dmesgparser.go (about)

     1  package dmesgparser
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"strconv"
     7  	"strings"
     8  	"sync"
     9  )
    10  
    11  // Dmesg struct handle for the dmesg parser
    12  type Dmesg struct {
    13  	chanSize          int
    14  	lastProcessedTime float64
    15  	sync.Mutex
    16  }
    17  
    18  func getEntryTime(line string) float64 {
    19  	leftindex := strings.Index(line, "[")
    20  	rightIndex := strings.Index(line, "]")
    21  	val, _ := strconv.ParseFloat(strings.TrimSpace(line[leftindex+1:rightIndex]), 64)
    22  	return val
    23  }
    24  
    25  // TODOD move to Dmesg -w mode later
    26  // func (r *Dmesg) runDmesgCommandFollowMode(outputChan chan string, interval time.Duration) {
    27  // 	cmdCtx,cancel := context.WithTimeout(ctx, interval)
    28  // 	defer cancel()
    29  // 	cmd := exec.CommandContext(, "dmesg", "-w", "-l", "warn")
    30  
    31  // }
    32  
    33  // RunDmesgCommand runs the Dmesg command to capture raw Dmesg output
    34  func (d *Dmesg) RunDmesgCommand() ([]string, error) {
    35  
    36  	output, err := exec.Command("dmesg").CombinedOutput()
    37  	if err != nil {
    38  		return nil, fmt.Errorf("Cannot run Dmesg cmd %s", err)
    39  	}
    40  
    41  	return d.ParseDmesgOutput(string(output))
    42  }
    43  
    44  // ParseDmesgOutput will parse dmesg output
    45  func (d *Dmesg) ParseDmesgOutput(dmesgOutput string) ([]string, error) {
    46  	lines := strings.Split(strings.TrimSuffix(dmesgOutput, "\n"), "\n")
    47  	outputslice := make([]string, len(lines))
    48  	elementsadded := 0
    49  
    50  	for _, line := range lines {
    51  		line = strings.TrimSpace(line)
    52  		if !isTraceOutput(line) {
    53  			continue
    54  		}
    55  		if d.lastProcessedTime < getEntryTime(line) {
    56  			outputslice[elementsadded] = line
    57  			elementsadded++
    58  		}
    59  	}
    60  	return outputslice[:elementsadded], nil
    61  }
    62  
    63  func isTraceOutput(line string) bool {
    64  	i := strings.Index(line, "]")
    65  	if i < 0 {
    66  		return false
    67  	}
    68  	substring := strings.TrimSpace(line[:strings.Index(line, "]")+1])
    69  	return strings.HasPrefix(line, substring+" TRACE:")
    70  }
    71  
    72  // New return an initialized Dmesg
    73  func New() *Dmesg {
    74  	return &Dmesg{
    75  		chanSize:          10000,
    76  		lastProcessedTime: 0,
    77  	}
    78  }