github.com/fastest963/consul@v1.4.5/command/intention/check/check.go (about)

     1  package check
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"io"
     7  
     8  	"github.com/hashicorp/consul/api"
     9  	"github.com/hashicorp/consul/command/flags"
    10  	"github.com/mitchellh/cli"
    11  )
    12  
    13  func New(ui cli.Ui) *cmd {
    14  	c := &cmd{UI: ui}
    15  	c.init()
    16  	return c
    17  }
    18  
    19  type cmd struct {
    20  	UI    cli.Ui
    21  	flags *flag.FlagSet
    22  	http  *flags.HTTPFlags
    23  	help  string
    24  
    25  	// testStdin is the input for testing.
    26  	testStdin io.Reader
    27  }
    28  
    29  func (c *cmd) init() {
    30  	c.flags = flag.NewFlagSet("", flag.ContinueOnError)
    31  	c.http = &flags.HTTPFlags{}
    32  	flags.Merge(c.flags, c.http.ClientFlags())
    33  	flags.Merge(c.flags, c.http.ServerFlags())
    34  	c.help = flags.Usage(help, c.flags)
    35  }
    36  
    37  func (c *cmd) Run(args []string) int {
    38  	if err := c.flags.Parse(args); err != nil {
    39  		return 2
    40  	}
    41  
    42  	args = c.flags.Args()
    43  	if len(args) != 2 {
    44  		c.UI.Error(fmt.Sprintf("Error: command requires exactly two arguments: src and dst"))
    45  		return 2
    46  	}
    47  
    48  	// Create and test the HTTP client
    49  	client, err := c.http.APIClient()
    50  	if err != nil {
    51  		c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
    52  		return 2
    53  	}
    54  
    55  	// Check the intention
    56  	allowed, _, err := client.Connect().IntentionCheck(&api.IntentionCheck{
    57  		Source:      args[0],
    58  		Destination: args[1],
    59  		SourceType:  api.IntentionSourceConsul,
    60  	}, nil)
    61  	if err != nil {
    62  		c.UI.Error(fmt.Sprintf("Error checking the connection: %s", err))
    63  		return 2
    64  	}
    65  
    66  	if allowed {
    67  		c.UI.Output("Allowed")
    68  		return 0
    69  	}
    70  
    71  	c.UI.Output("Denied")
    72  	return 1
    73  }
    74  
    75  func (c *cmd) Synopsis() string {
    76  	return synopsis
    77  }
    78  
    79  func (c *cmd) Help() string {
    80  	return c.help
    81  }
    82  
    83  const synopsis = "Check whether a connection between two services is allowed."
    84  const help = `
    85  Usage: consul intention check [options] SRC DST
    86  
    87    Check whether a connection between SRC and DST would be allowed by
    88    Connect given the current Consul configuration.
    89  
    90        $ consul intention check web db
    91  
    92  `