github.hscsec.cn/hashicorp/consul@v1.4.5/command/intention/match/match.go (about) 1 package match 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 // flags 26 flagSource bool 27 flagDestination bool 28 29 // testStdin is the input for testing. 30 testStdin io.Reader 31 } 32 33 func (c *cmd) init() { 34 c.flags = flag.NewFlagSet("", flag.ContinueOnError) 35 c.flags.BoolVar(&c.flagSource, "source", false, 36 "Match intentions with the given source.") 37 c.flags.BoolVar(&c.flagDestination, "destination", false, 38 "Match intentions with the given destination.") 39 40 c.http = &flags.HTTPFlags{} 41 flags.Merge(c.flags, c.http.ClientFlags()) 42 flags.Merge(c.flags, c.http.ServerFlags()) 43 c.help = flags.Usage(help, c.flags) 44 } 45 46 func (c *cmd) Run(args []string) int { 47 if err := c.flags.Parse(args); err != nil { 48 return 2 49 } 50 51 args = c.flags.Args() 52 if len(args) != 1 { 53 c.UI.Error(fmt.Sprintf("Error: command requires exactly one argument: src or dst")) 54 return 1 55 } 56 57 if c.flagSource && c.flagDestination { 58 c.UI.Error(fmt.Sprintf("Error: only one of -source or -destination may be specified")) 59 return 1 60 } 61 62 by := api.IntentionMatchDestination 63 if c.flagSource { 64 by = api.IntentionMatchSource 65 } 66 67 // Create and test the HTTP client 68 client, err := c.http.APIClient() 69 if err != nil { 70 c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err)) 71 return 1 72 } 73 74 // Match the intention 75 matches, _, err := client.Connect().IntentionMatch(&api.IntentionMatch{ 76 By: by, 77 Names: []string{args[0]}, 78 }, nil) 79 if err != nil { 80 c.UI.Error(fmt.Sprintf("Error matching the connection: %s", err)) 81 return 1 82 } 83 84 for _, ixn := range matches[args[0]] { 85 c.UI.Output(ixn.String()) 86 } 87 88 return 0 89 } 90 91 func (c *cmd) Synopsis() string { 92 return synopsis 93 } 94 95 func (c *cmd) Help() string { 96 return c.help 97 } 98 99 const synopsis = "Show intentions that match a source or destination." 100 const help = ` 101 Usage: consul intention match [options] SRC|DST 102 103 Show the list of intentions that would be enforced for a given source 104 or destination. The intentions are listed in the order they would be 105 evaluated. 106 107 $ consul intention match db 108 $ consul intention match -source web 109 110 `