Skip to content

Commit 6342b05

Browse files
committed
adds context to run, so that we can call cancelation later
1 parent 84fd588 commit 6342b05

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

cmd/run.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ limitations under the License.
1616
package cmd
1717

1818
import (
19+
"context"
1920
"fmt"
2021
"os"
2122
"time"
@@ -39,6 +40,7 @@ example: tagit run -s my-super-service -x '/tmp/tag-role.sh'
3940
script := cmd.PersistentFlags().Lookup("script").Value.String()
4041
tagPrefix := cmd.PersistentFlags().Lookup("tag-prefix").Value.String()
4142
interval := cmd.PersistentFlags().Lookup("interval").Value.String()
43+
ctx := context.Background()
4244

4345
if serviceID == "" {
4446
fmt.Println("service-id is required")
@@ -71,7 +73,7 @@ example: tagit run -s my-super-service -x '/tmp/tag-role.sh'
7173
}
7274

7375
t := tagit.New(tagit.NewConsulAPIWrapper(consulClient), &tagit.CmdExecutor{}, serviceID, script, validInterval, tagPrefix)
74-
t.Run()
76+
t.Run(ctx)
7577
},
7678
}
7779

pkg/tagit/tagit.go

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package tagit
22

33
import (
4+
"context"
45
"fmt"
56
"os/exec"
67
"strings"
@@ -77,16 +78,22 @@ func New(consulClient ConsulClient, commandExecutor CommandExecutor, serviceID s
7778
}
7879

7980
// Run will run the tagit flow and tag consul services based on the script output
80-
func (t *TagIt) Run() {
81+
func (t *TagIt) Run(ctx context.Context) {
82+
ticker := time.NewTicker(t.Interval)
8183
for {
82-
err := t.updateServiceTags()
83-
if err != nil {
84-
log.WithFields(log.Fields{
85-
"service": t.ServiceID,
86-
"error": err,
87-
}).Error("error updating service tags")
84+
select {
85+
case <-ctx.Done():
86+
ticker.Stop()
87+
return
88+
case <-ticker.C:
89+
err := t.updateServiceTags()
90+
if err != nil {
91+
log.WithFields(log.Fields{
92+
"service": t.ServiceID,
93+
"error": err,
94+
}).Error("error updating service tags")
95+
}
8896
}
89-
time.Sleep(t.Interval)
9097
}
9198
}
9299

0 commit comments

Comments
 (0)