Skip to content

Commit

Permalink
Merge pull request #14909 from r-vasquez/rpk-partitions-disable-enable
Browse files Browse the repository at this point in the history
rpk: add `cluster partitions enable/disable`
  • Loading branch information
twmb authored Nov 22, 2023
2 parents ebe680e + 432ac93 commit 20f2889
Show file tree
Hide file tree
Showing 5 changed files with 361 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/go/rpk/pkg/adminapi/api_partition.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,21 @@ func (a *AdminAPI) MoveReplicas(ctx context.Context, ns string, topic string, pa
r,
nil)
}

// ToggleAllTopicPartitions will toggle all partitions in the given topic.
func (a *AdminAPI) ToggleAllTopicPartitions(ctx context.Context, disabled bool, namespace, topic string) error {
disableURL := fmt.Sprintf("%v/%v/%v", partitionsBaseURL, namespace, topic)
body := struct {
Disabled bool `json:"disabled"`
}{disabled}
return a.sendToLeader(ctx, http.MethodPost, disableURL, body, nil)
}

// ToggleTopicPartitions will toggle the given partitions in the given topic.
func (a *AdminAPI) ToggleTopicPartitions(ctx context.Context, disabled bool, namespace, topic string, partition int) error {
disableURL := fmt.Sprintf("%v/%v/%v/%v", partitionsBaseURL, namespace, topic, partition)
body := struct {
Disabled bool `json:"disabled"`
}{disabled}
return a.sendToLeader(ctx, http.MethodPost, disableURL, body, nil)
}
12 changes: 12 additions & 0 deletions src/go/rpk/pkg/cli/cluster/partitions/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,18 @@ replicas assignments in the form of: <Node-ID>-<Core>.
If the DISABLED column contains a '-' value, then it means you are running this
command against a cluster that does not support the underlying API.
ENABLED/DISABLED
Disabling a partition in Redpanda involves prohibiting any data consumption or
production to and from it. All internal processes associated with the partition
are stopped, and it remains unloaded during system startup. This measure aims to
maintain cluster health by preventing issues caused by specific corrupted
partitions that may lead to Redpanda crashes. Although the data remains stored
on disk, Redpanda ceases interaction with the disabled partitions to ensure
system stability.
You may disable/enable partition using 'rpk cluster partitions enable/disable'.
EXAMPLES
List all partitions in the cluster.
Expand Down
2 changes: 2 additions & 0 deletions src/go/rpk/pkg/cli/cluster/partitions/partitions.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ func NewPartitionsCommand(fs afero.Fs, p *config.Params) *cobra.Command {
newListCommand(fs, p),
newMovementCancelCommand(fs, p),
newMovementCancelCommandHidden(fs, p),
newPartitionDisableCommand(fs, p),
newPartitionEnableCommand(fs, p),
newPartitionMovementsStatusCommand(fs, p),
)
return cmd
Expand Down
243 changes: 243 additions & 0 deletions src/go/rpk/pkg/cli/cluster/partitions/toggle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
// Copyright 2023 Redpanda Data, Inc.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.md
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0

package partitions

import (
"context"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"sync"

"github.com/redpanda-data/redpanda/src/go/rpk/pkg/adminapi"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/config"
"github.com/redpanda-data/redpanda/src/go/rpk/pkg/out"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)

func newPartitionEnableCommand(fs afero.Fs, p *config.Params) *cobra.Command {
var (
partitions []string
all bool
)
cmd := &cobra.Command{
Use: "enable [TOPIC]",
Short: "Enable partitions of a topic",
Long: `Enable partitions of a topic
You may enable all partitions of a topic using the --all flag or you may select
a set of topic/partitions to enable with the '--partitions/-p' flag.
The partition flag accepts the format {namespace}/{topic}/[partitions...]
where namespace and topic are optional parameters. If the namespace is not
provided, rpk will assume 'kafka'. If the topic is not provided in the flag, rpk
will use the topic provided as an argument to this command.
EXAMPLES
Enable all partitions in topic 'foo'
rpk cluster partitions enable foo --all
Enable partitions 1,2 and 3 of topic 'bar' in the namespace 'internal'
rpk cluster partitions enable internal/bar --partitions 1,2,3
Enable partition 1, and 2 of topic 'foo', and partition 5 of topic 'bar' in the
'internal' namespace'
rpk cluster partitions enable -p foo/1,2 -p internal/bar/5
`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, topicArg []string) {
if !all && partitions == nil {
fmt.Println("Please select either specific partitions to enable (--partitions) or select all (--all).")
cmd.Help()
os.Exit(1)
}
if all && len(topicArg) == 0 {
fmt.Println("You must select a topic.")
cmd.Help()
os.Exit(1)
}
p, err := p.LoadVirtualProfile(fs)
out.MaybeDie(err, "unable to load config: %v", err)
out.CheckExitCloudAdmin(p)

cl, err := adminapi.NewClient(fs, p)
out.MaybeDie(err, "unable to initialize admin client: %v", err)

err = runToggle(cmd.Context(), cl, all, topicArg, partitions, "enable")
out.MaybeDieErr(err)
if len(partitions) == 0 {
fmt.Printf("Successfully enabled all partitions in topic %v\n", topicArg[0])
} else {
fmt.Printf("Successfully enabled the partitions %v\n", partitions)
}
},
}
cmd.Flags().StringArrayVarP(&partitions, "partitions", "p", nil, "Comma-separated list of partitions you want to enable. Check help for extended usage")
cmd.Flags().BoolVarP(&all, "all", "a", false, "If true, enable all partitions for the specified topic")

cmd.MarkFlagsMutuallyExclusive("partitions", "all")
return cmd
}

func newPartitionDisableCommand(fs afero.Fs, p *config.Params) *cobra.Command {
var (
partitions []string
all bool
)
cmd := &cobra.Command{
Use: "disable [TOPIC]",
Short: "Disable partitions of a topic",
Long: `Disable partitions of a topic
You may disable all partitions of a topic using the --all flag or you may select
a set of topic/partitions to disable with the '--partitions/-p' flag.
The partition flag accepts the format {namespace}/{topic}/[partitions...]
where namespace and topic are optional parameters. If the namespace is not
provided, rpk will assume 'kafka'. If the topic is not provided in the flag, rpk
will use the topic provided as an argument to this command.
DISABLED PARTITIONS
Disabling a partition in Redpanda involves prohibiting any data consumption or
production to and from it. All internal processes associated with the partition
are stopped, and it remains unloaded during system startup. This measure aims to
maintain cluster health by preventing issues caused by specific corrupted
partitions that may lead to Redpanda crashes. Although the data remains stored
on disk, Redpanda ceases interaction with the disabled partitions to ensure
system stability.
EXAMPLES
Disable all partitions in topic 'foo'
rpk cluster partitions disable foo --all
Disable partitions 1,2 and 3 of topic 'bar' in the namespace 'internal'
rpk cluster partitions disable internal/bar --partitions 1,2,3
Disable partition 1, and 2 of topic 'foo', and partition 5 of topic 'bar' in the
'internal' namespace'
rpk cluster partitions disable -p foo/1,2 -p internal/bar/5
`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, topicArg []string) {
if !all && partitions == nil {
fmt.Println("Please select either specific partitions to disable (--partitions) or select all (--all).")
cmd.Help()
os.Exit(1)
}
if all && len(topicArg) == 0 {
fmt.Println("You must select a topic.")
cmd.Help()
os.Exit(1)
}
p, err := p.LoadVirtualProfile(fs)
out.MaybeDie(err, "unable to load config: %v", err)
out.CheckExitCloudAdmin(p)

cl, err := adminapi.NewClient(fs, p)
out.MaybeDie(err, "unable to initialize admin client: %v", err)

err = runToggle(cmd.Context(), cl, all, topicArg, partitions, "disable")
out.MaybeDieErr(err)
if all {
fmt.Printf("Successfully disabled all partitions in topic %v\n", topicArg[0])
} else {
fmt.Printf("Successfully disabled the partitions %v\n", partitions)
}
},
}
cmd.Flags().StringArrayVarP(&partitions, "partitions", "p", nil, "Comma-separated list of partitions you want to disable. Use --help for additional information")
cmd.Flags().BoolVarP(&all, "all", "a", false, "If true, disable all partitions for the specified topic")

cmd.MarkFlagsMutuallyExclusive("partitions", "all")
return cmd
}

func runToggle(ctx context.Context, cl *adminapi.AdminAPI, all bool, topicArg, partitionFlag []string, verb string) error {
isDisable := verb == "disable"
if all {
ns, topicName := nsTopic(topicArg[0])
err := cl.ToggleAllTopicPartitions(ctx, isDisable, ns, topicName)
if err != nil {
return fmt.Errorf("failed to %v all partitions in topic %v/%v: %v", verb, ns, topicName, err)
}
return nil
}
g, egCtx := errgroup.WithContext(ctx)
for _, ntp := range partitionFlag {
ns, topicName, partitions, err := parsePartition(ntp)
if err != nil {
return err
}
if topicName != "" && len(topicArg) > 0 && topicArg[0] != "" {
return fmt.Errorf("unable to run the command: topic cannot be specified both as an argument and in the --partition flag")
}
if topicName == "" {
if len(topicArg) == 0 {
return fmt.Errorf("unable to run the command: you must specify the topic either as an argument or in the --partition flag")
}
topicName = topicArg[0]
}
for _, p := range partitions {
p := p
g.Go(func() error {
err := cl.ToggleTopicPartitions(egCtx, isDisable, ns, topicName, p)
if err != nil {
return fmt.Errorf("failed to %v partition %v in topic %v/%v: %v", verb, p, ns, topicName, err)
}
return nil
})
}
}
return g.Wait()
}

var (
partitionRe *regexp.Regexp
partitionReOnce sync.Once
)

// parsePartition parses the partition flag with the format:
// {namespace}/{topic}/[partitions...]
// where namespace and topic are optionals, and partitions are comma-separated
// partitions ID. If namespace is not provided, the function assumes 'kafka'.
func parsePartition(ntp string) (ns, topic string, partitions []int, rerr error) {
partitionReOnce.Do(func() {
// Matches {namespace}/{topic}/[partitions...]
// - Index 0: Full Match.
// - Index 1: Namespace, if present.
// - Index 2: Topic, if present.
// - Index 3: Comma-separated partitions.
partitionRe = regexp.MustCompile(`^(?:(?:([^/]+)/)?([^/]+)/)?(\d+(?:,\d+)*)$`)
})
match := partitionRe.FindStringSubmatch(ntp)
if len(match) == 0 {
return "", "", nil, fmt.Errorf("unable to parse %q: wrong format", ntp)
}
ns = match[1]
if ns == "" {
ns = "kafka"
}
partitionString := strings.Split(match[3], ",")
for _, str := range partitionString {
p, err := strconv.Atoi(str)
if err != nil {
return "", "", nil, fmt.Errorf("unable to parse partition %v in flag %v: %v", str, ntp, err)
}
partitions = append(partitions, p)
}
return ns, match[2], partitions, nil
}
86 changes: 86 additions & 0 deletions src/go/rpk/pkg/cli/cluster/partitions/toggle_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright 2023 Redpanda Data, Inc.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.md
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0

package partitions

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_parsePartition(t *testing.T) {
for _, tt := range []struct {
name string
input string
expNs string
expTopic string
expPartitions []int
expErr bool
}{
{
name: "complete",
input: "_redpanda_internal/topic-foo1/2,3,1",
expNs: "_redpanda_internal",
expTopic: "topic-foo1",
expPartitions: []int{2, 3, 1},
}, {
name: "topic and partitions",
input: "myTopic/1,2",
expNs: "kafka",
expTopic: "myTopic",
expPartitions: []int{1, 2},
}, {
name: "topic and single partition",
input: "myTopic/12",
expNs: "kafka",
expTopic: "myTopic",
expPartitions: []int{12},
}, {
name: "just partitions",
input: "1,2,3,5,8,13,21",
expNs: "kafka",
expTopic: "",
expPartitions: []int{1, 2, 3, 5, 8, 13, 21},
}, {
name: "single partition",
input: "13",
expNs: "kafka",
expTopic: "",
expPartitions: []int{13},
}, {
name: "topic with dot",
input: "my.topic.foo/1",
expNs: "kafka",
expTopic: "my.topic.foo",
expPartitions: []int{1},
}, {
name: "wrong format 1",
input: "thirteen",
expErr: true,
}, {
name: "wrong format 2",
input: "_internal|foo|1,2,3",
expErr: true,
},
} {
t.Run(tt.name, func(t *testing.T) {
gotNs, gotTopic, gotPartitions, err := parsePartition(tt.input)
if tt.expErr {
require.Error(t, err)
return
}
require.NoError(t, err)

require.Equal(t, tt.expNs, gotNs)
require.Equal(t, tt.expTopic, gotTopic)
require.Equal(t, tt.expPartitions, gotPartitions)
})
}
}

0 comments on commit 20f2889

Please sign in to comment.