github.com/netdata/go.d.plugin@v0.58.1/modules/nvme/init.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package nvme
     4  
     5  import (
     6  	"context"
     7  	"errors"
     8  	"fmt"
     9  	"os"
    10  	"os/exec"
    11  	"path/filepath"
    12  )
    13  
    14  func (n *NVMe) validateConfig() error {
    15  	if n.BinaryPath == "" {
    16  		return errors.New("'binary_path' can not be empty")
    17  	}
    18  
    19  	return nil
    20  }
    21  
    22  func (n *NVMe) initNVMeCLIExec() (nvmeCLI, error) {
    23  	if exePath, err := os.Executable(); err == nil {
    24  		ndsudoPath := filepath.Join(filepath.Dir(exePath), "ndsudo")
    25  
    26  		if fi, err := os.Stat(ndsudoPath); err == nil {
    27  			// executable by owner or group
    28  			if fi.Mode().Perm()&0110 != 0 {
    29  				n.Debug("using ndsudo")
    30  				return &nvmeCLIExec{
    31  					ndsudoPath: ndsudoPath,
    32  					timeout:    n.Timeout.Duration,
    33  				}, nil
    34  			}
    35  		}
    36  	}
    37  
    38  	// TODO: remove after next minor release of Netdata (latest is v1.44.0)
    39  	// can't remove now because it will break "from source + stable channel" installations
    40  	nvmePath, err := exec.LookPath(n.BinaryPath)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	var sudoPath string
    46  	if os.Getuid() != 0 {
    47  		sudoPath, err = exec.LookPath("sudo")
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  	}
    52  
    53  	if sudoPath != "" {
    54  		ctx1, cancel1 := context.WithTimeout(context.Background(), n.Timeout.Duration)
    55  		defer cancel1()
    56  
    57  		if _, err := exec.CommandContext(ctx1, sudoPath, "-n", "-v").Output(); err != nil {
    58  			return nil, fmt.Errorf("can not run sudo on this host: %v", err)
    59  		}
    60  
    61  		ctx2, cancel2 := context.WithTimeout(context.Background(), n.Timeout.Duration)
    62  		defer cancel2()
    63  
    64  		if _, err := exec.CommandContext(ctx2, sudoPath, "-n", "-l", nvmePath).Output(); err != nil {
    65  			return nil, fmt.Errorf("can not run '%s' with sudo: %v", n.BinaryPath, err)
    66  		}
    67  	}
    68  
    69  	return &nvmeCLIExec{
    70  		sudoPath: sudoPath,
    71  		nvmePath: nvmePath,
    72  		timeout:  n.Timeout.Duration,
    73  	}, nil
    74  }