Skip to content

Commit

Permalink
add filter flag and remove automatation
Browse files Browse the repository at this point in the history
  • Loading branch information
wangxinyi7 committed Aug 23, 2024
1 parent 0a9a7cb commit a211357
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 115 deletions.
2 changes: 1 addition & 1 deletion .changelog/4255.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
```release-note:bug
sync-catalog: After running `helm upgrade` with `syncCatalog` disabled, the registered K8S services should be removed from consul.
sync-catalog: Enable the user to purge the registered services by passing parent node and necessary filters.
```

This file was deleted.

3 changes: 3 additions & 0 deletions charts/consul/templates/sync-catalog-serviceaccount.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
{{- $syncEnabled := (or (and (ne (.Values.syncCatalog.enabled | toString) "-") .Values.syncCatalog.enabled) (and (eq (.Values.syncCatalog.enabled | toString) "-") .Values.global.enabled)) }}
{{- if $syncEnabled }}
apiVersion: v1
kind: ServiceAccount
metadata:
Expand All @@ -19,3 +21,4 @@ imagePullSecrets:
- name: {{ .name }}
{{- end }}
{{- end }}
{{- end }}
22 changes: 21 additions & 1 deletion control-plane/subcommand/sync-catalog/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
package synccatalog

import (
"bufio"
"context"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"regexp"
"strings"
"sync"
"syscall"
"time"
Expand Down Expand Up @@ -60,6 +62,7 @@ type Command struct {
flagLogLevel string
flagLogJSON bool
flagPurgeK8SServices bool
flagFilter string

// Flags to support namespaces
flagEnableNamespaces bool // Use namespacing on all components
Expand Down Expand Up @@ -142,6 +145,8 @@ func (c *Command) init() {
"Enable or disable JSON output format for logging.")
c.flags.BoolVar(&c.flagPurgeK8SServices, "purge-k8s-services", false,
"Purge all K8S services registered in Consul.")
c.flags.StringVar(&c.flagFilter, "filter", "",
"Specifies the expression used to filter the queries results for the node.")

c.flags.Var((*flags.AppendSliceValue)(&c.flagAllowK8sNamespacesList), "allow-k8s-namespace",
"K8s namespaces to explicitly allow. May be specified multiple times.")
Expand Down Expand Up @@ -412,7 +417,7 @@ func (c *Command) Run(args []string) int {

// remove all k8s services from Consul.
func (c *Command) removeAllK8SServicesFromConsulNode(consulClient *api.Client, nodeName string) error {
node, _, err := consulClient.Catalog().NodeServiceList(nodeName, nil)
node, _, err := consulClient.Catalog().NodeServiceList(nodeName, &api.QueryOptions{Filter: c.flagFilter})
if err != nil {
return err
}
Expand All @@ -424,6 +429,21 @@ func (c *Command) removeAllK8SServicesFromConsulNode(consulClient *api.Client, n
maxRetries := 2
retryDelay := 200 * time.Millisecond

// Ask for user confirmation
reader := bufio.NewReader(os.Stdin)
for {
c.UI.Info(fmt.Sprintf("Are you sure you want to delete %v K8S services from %v? (y/n): ", len(services), nodeName))
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input == "y" || input == "Y" {
break
} else if input == "n" || input == "N" {
return nil
} else {
c.UI.Info("Invalid input. Please enter 'y' or 'n'.")
}
}

for i := 0; i < len(services); i += batchSize {
end := i + batchSize
if end > len(services) {
Expand Down
18 changes: 16 additions & 2 deletions control-plane/subcommand/sync-catalog/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -577,9 +577,23 @@ func TestRemoveAllK8SServicesFromConsul(t *testing.T) {
t.Parallel()

k8s, testClient := completeSetup(t)

consulClient := testClient.APIClient

// Create a mock reader to simulate user input
input := "y\n"
reader, writer, err := os.Pipe()
require.NoError(t, err)
oldStdin := os.Stdin
os.Stdin = reader
defer func() { os.Stdin = oldStdin }()

// Write the simulated user input to the mock reader
go func() {
defer writer.Close()
_, err := writer.WriteString(input)
require.NoError(t, err)
}()

// Run the command.
ui := cli.NewMockUi()
cmd := Command{
Expand All @@ -594,7 +608,7 @@ func TestRemoveAllK8SServicesFromConsul(t *testing.T) {
}

// create two services in k8s
_, err := k8s.CoreV1().Services("bar").Create(context.Background(), lbService("foo", "1.1.1.1"), metav1.CreateOptions{})
_, err = k8s.CoreV1().Services("bar").Create(context.Background(), lbService("foo", "1.1.1.1"), metav1.CreateOptions{})
require.NoError(t, err)

_, err = k8s.CoreV1().Services("baz").Create(context.Background(), lbService("foo", "2.2.2.2"), metav1.CreateOptions{})
Expand Down

0 comments on commit a211357

Please sign in to comment.