github.com/jenkins-x/jx/v2@v2.1.155/pkg/kube/logs.go (about)

     1  package kube
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  
    11  	"github.com/jenkins-x/jx-logging/pkg/log"
    12  	"github.com/jenkins-x/jx/v2/pkg/util"
    13  	"github.com/pkg/errors"
    14  )
    15  
    16  // TailLogs will tail the logs for the pod in ns with containerName,
    17  // returning when the logs are complete. It writes to errOut and out.
    18  func TailLogs(ns string, pod string, containerName string, errOut io.Writer, out io.Writer) error {
    19  	args := []string{"logs", "-n", ns, "-f"}
    20  	if containerName != "" {
    21  		args = append(args, "-c", containerName)
    22  	}
    23  	args = append(args, pod)
    24  	name := "kubectl"
    25  	e := exec.Command(name, args...)
    26  	e.Stderr = errOut
    27  	stdout, _ := e.StdoutPipe()
    28  
    29  	err := os.Setenv("PATH", util.PathWithBinary())
    30  	if err != nil {
    31  		return errors.Wrap(err, "failed to set PATH env variable")
    32  	}
    33  	err = e.Start()
    34  	if err != nil {
    35  		log.Logger().Errorf("Error: Command failed  %s %s", name, strings.Join(args, " "))
    36  	}
    37  
    38  	scanner := bufio.NewScanner(stdout)
    39  	scanner.Split(bufio.ScanLines)
    40  	for scanner.Scan() {
    41  		m := scanner.Text()
    42  		_, err = fmt.Fprintln(out, m)
    43  		if err != nil {
    44  			return err
    45  		}
    46  		if m == "Finished: FAILURE" {
    47  			os.Exit(1)
    48  		}
    49  	}
    50  	err = e.Wait()
    51  	if err != nil {
    52  		return err
    53  	}
    54  	return nil
    55  }