github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/cmd/compliance/compliance_logs.go (about)

     1  package compliance
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  
     8  	"github.com/olli-ai/jx/v2/pkg/cmd/helper"
     9  
    10  	"github.com/heptio/sonobuoy/pkg/client"
    11  	"github.com/olli-ai/jx/v2/pkg/cmd/opts"
    12  	"github.com/olli-ai/jx/v2/pkg/cmd/templates"
    13  	"github.com/pkg/errors"
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  const (
    18  	bufSize = 2048
    19  )
    20  
    21  var (
    22  	complianceLogsLongs = templates.LongDesc(`
    23  		Prints the logs of compliance tests
    24  	`)
    25  
    26  	complianceLogsExample = templates.Examples(`
    27  		# Print the compliance logs
    28  		jx compliance logs
    29  	`)
    30  )
    31  
    32  // ComplianceLogsOptions options for "compliance logs" command
    33  type ComplianceLogsOptions struct {
    34  	*opts.CommonOptions
    35  
    36  	Follow bool
    37  }
    38  
    39  // NewCmdComplianceLogs creates a command object for the "compliance logs" action, which
    40  // prints the logs of compliance tests
    41  func NewCmdComplianceLogs(commonOpts *opts.CommonOptions) *cobra.Command {
    42  	options := &ComplianceLogsOptions{
    43  		CommonOptions: commonOpts,
    44  	}
    45  
    46  	cmd := &cobra.Command{
    47  		Use:     "logs",
    48  		Short:   "Prints the logs of compliance tests",
    49  		Long:    complianceLogsLongs,
    50  		Example: complianceLogsExample,
    51  		Run: func(cmd *cobra.Command, args []string) {
    52  			options.Cmd = cmd
    53  			options.Args = args
    54  			err := options.Run()
    55  			helper.CheckErr(err)
    56  		},
    57  	}
    58  
    59  	cmd.Flags().BoolVarP(&options.Follow, "follow", "f", false, "Specify if the logs should be streamed.")
    60  
    61  	return cmd
    62  }
    63  
    64  // Run implements the "compliance logs" command
    65  func (o *ComplianceLogsOptions) Run() error {
    66  	cc, err := o.ComplianceClient()
    67  	if err != nil {
    68  		return errors.Wrap(err, "could not create the compliance client")
    69  	}
    70  	logConfig := &client.LogConfig{
    71  		Follow:    o.Follow,
    72  		Namespace: complianceNamespace,
    73  		Out:       os.Stdout,
    74  	}
    75  	logReader, err := cc.LogReader(logConfig)
    76  	if err != nil {
    77  		return errors.Wrap(err, "could not create the logs reader")
    78  	}
    79  
    80  	b := make([]byte, bufSize)
    81  	for {
    82  		n, err := logReader.Read(b)
    83  		if err != nil && err != io.EOF {
    84  			return errors.Wrap(err, "error reading the logs")
    85  		}
    86  		fmt.Fprint(logConfig.Out, string(b[:n]))
    87  		if err == io.EOF {
    88  			return nil
    89  		}
    90  	}
    91  }