command/intention/create: -replace does an atomic change

This commit is contained in:
Mitchell Hashimoto 2018-05-16 08:55:33 -07:00
parent 3a6a750972
commit be82b94f81
No known key found for this signature in database
GPG Key ID: 744E147AA52F5B0A
1 changed files with 11 additions and 6 deletions

View File

@ -45,8 +45,7 @@ func (c *cmd) init() {
c.flags.BoolVar(&c.flagFile, "file", false, c.flags.BoolVar(&c.flagFile, "file", false,
"Read intention data from one or more files.") "Read intention data from one or more files.")
c.flags.BoolVar(&c.flagReplace, "replace", false, c.flags.BoolVar(&c.flagReplace, "replace", false,
"Replace matching intentions. This is not an atomic operation. "+ "Replace matching intentions.")
"If the insert fails, then the previous intention will still be deleted.")
c.flags.Var((*flags.FlagMapValue)(&c.flagMeta), "meta", c.flags.Var((*flags.FlagMapValue)(&c.flagMeta), "meta",
"Metadata to set on the intention, formatted as key=value. This flag "+ "Metadata to set on the intention, formatted as key=value. This flag "+
"may be specified multiple times to set multiple meta fields.") "may be specified multiple times to set multiple meta fields.")
@ -95,7 +94,7 @@ func (c *cmd) Run(args []string) int {
for _, ixn := range ixns { for _, ixn := range ixns {
// If replace is set to true, then find this intention and delete it. // If replace is set to true, then find this intention and delete it.
if c.flagReplace { if c.flagReplace {
ixn, err := find.Find(ixn.SourceString(), ixn.DestinationString()) oldIxn, err := find.Find(ixn.SourceString(), ixn.DestinationString())
if err != nil { if err != nil {
c.UI.Error(fmt.Sprintf( c.UI.Error(fmt.Sprintf(
"Error looking up intention for replacement with source %q "+ "Error looking up intention for replacement with source %q "+
@ -105,16 +104,22 @@ func (c *cmd) Run(args []string) int {
err)) err))
return 1 return 1
} }
if ixn != nil { if oldIxn != nil {
if _, err := client.Connect().IntentionDelete(ixn.ID, nil); err != nil { // We set the ID of our intention so we overwrite it
ixn.ID = oldIxn.ID
if _, err := client.Connect().IntentionUpdate(ixn, nil); err != nil {
c.UI.Error(fmt.Sprintf( c.UI.Error(fmt.Sprintf(
"Error deleting intention for replacement with source %q "+ "Error replacing intention with source %q "+
"and destination %q: %s", "and destination %q: %s",
ixn.SourceString(), ixn.SourceString(),
ixn.DestinationString(), ixn.DestinationString(),
err)) err))
return 1 return 1
} }
// Continue since we don't want to try to insert a new intention
continue
} }
} }