Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

info subcommand #165

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/help/gardenctl.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Find more information at: https://github.com/gardener/gardenctl-v2/blob/master/R
### SEE ALSO

* [gardenctl config](gardenctl_config.md) - Modify gardenctl configuration file using subcommands
* [gardenctl info](gardenctl_info.md) - Get landscape informations and shows the number of shoots per seed, e.g. "gardenctl info"
* [gardenctl kubeconfig](gardenctl_kubeconfig.md) - Print the kubeconfig for the current target
* [gardenctl kubectl-env](gardenctl_kubectl-env.md) - Generate a script that points KUBECONFIG to the targeted cluster for the specified shell
* [gardenctl provider-env](gardenctl_provider-env.md) - Generate the cloud provider CLI configuration script for the specified shell
Expand Down
37 changes: 37 additions & 0 deletions docs/help/gardenctl_info.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
## gardenctl info

Get landscape informations and shows the number of shoots per seed, e.g. "gardenctl info"

```
gardenctl info [flags]
```

### Options

```
-h, --help help for info
```

### Options inherited from parent commands

```
--add-dir-header If true, adds the file directory to the header of the log messages
--alsologtostderr log to standard error as well as files (no effect when -logtostderr=true)
--config string config file (default is ~/.garden/gardenctl-v2.yaml)
--log-backtrace-at traceLocation when logging hits line file:N, emit a stack trace (default :0)
--log-dir string If non-empty, write log files in this directory (no effect when -logtostderr=true)
--log-file string If non-empty, use this log file (no effect when -logtostderr=true)
--log-file-max-size uint Defines the maximum size a log file can grow to (no effect when -logtostderr=true). Unit is megabytes. If the value is 0, the maximum file size is unlimited. (default 1800)
--logtostderr log to standard error instead of files (default true)
--one-output If true, only write logs to their native severity level (vs also writing to each lower severity level; no effect when -logtostderr=true)
--skip-headers If true, avoid header prefixes in the log messages
--skip-log-headers If true, avoid headers when opening log files (no effect when -logtostderr=true)
--stderrthreshold severity logs at or above this threshold go to stderr when writing to files and stderr (no effect when -logtostderr=true or -alsologtostderr=false) (default 2)
-v, --v Level number for the log level verbosity
--vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging
```

### SEE ALSO

* [gardenctl](gardenctl.md) - Gardenctl is a utility to interact with Gardener installations

2 changes: 2 additions & 0 deletions pkg/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/gardener/gardenctl-v2/internal/util"
cmdconfig "github.com/gardener/gardenctl-v2/pkg/cmd/config"
cmdenv "github.com/gardener/gardenctl-v2/pkg/cmd/env"
cmdinfo "github.com/gardener/gardenctl-v2/pkg/cmd/info"
"github.com/gardener/gardenctl-v2/pkg/cmd/kubeconfig"
cmdssh "github.com/gardener/gardenctl-v2/pkg/cmd/ssh"
cmdsshpatch "github.com/gardener/gardenctl-v2/pkg/cmd/sshpatch"
Expand Down Expand Up @@ -124,6 +125,7 @@ Find more information at: https://github.com/gardener/gardenctl-v2/blob/master/R
cmd.AddCommand(cmdenv.NewCmdKubectlEnv(f, ioStreams))
cmd.AddCommand(cmdenv.NewCmdRC(f, ioStreams))
cmd.AddCommand(kubeconfig.NewCmdKubeconfig(f, ioStreams))
cmd.AddCommand(cmdinfo.NewCmdInfo(f, cmdinfo.NewInfoOptions(ioStreams)))

return cmd
}
Expand Down
26 changes: 26 additions & 0 deletions pkg/cmd/info/info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Gardener contributors

SPDX-License-Identifier: Apache-2.0
*/

package info

import (
"github.com/spf13/cobra"

"github.com/gardener/gardenctl-v2/internal/util"
"github.com/gardener/gardenctl-v2/pkg/cmd/base"
)

// NewCmdInfo returns a new info command.
func NewCmdInfo(f util.Factory, o *Options) *cobra.Command {
cmd := &cobra.Command{
Use: "info",
Short: "Get landscape informations and shows the number of shoots per seed, e.g. \"gardenctl info\"",
Args: cobra.NoArgs,
RunE: base.WrapRunE(o, f),
}

return cmd
}
28 changes: 28 additions & 0 deletions pkg/cmd/info/info_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Gardener contributors

SPDX-License-Identifier: Apache-2.0
*/

package info_test

import (
"testing"

gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
operationsv1alpha1 "github.com/gardener/gardener/pkg/apis/operations/v1alpha1"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes/scheme"
)

func init() {
utilruntime.Must(gardencorev1beta1.AddToScheme(scheme.Scheme))
utilruntime.Must(operationsv1alpha1.AddToScheme(scheme.Scheme))
}

func TestCommand(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Info Command Test Suite")
}
114 changes: 114 additions & 0 deletions pkg/cmd/info/info_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Gardener contributors
SPDX-License-Identifier: Apache-2.0
*/

package info_test

import (
internalfake "github.com/gardener/gardenctl-v2/internal/fake"
"github.com/gardener/gardenctl-v2/internal/util"
cmdinfo "github.com/gardener/gardenctl-v2/pkg/cmd/info"
"github.com/gardener/gardenctl-v2/pkg/config"
"github.com/gardener/gardenctl-v2/pkg/target"
targetmocks "github.com/gardener/gardenctl-v2/pkg/target/mocks"

gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
)

var _ = Describe("Info Command", func() {
const (
gardenName = "mygarden"
)

var (
streams util.IOStreams
out *util.SafeBytesBuffer
factory *internalfake.Factory
targetProvider *internalfake.TargetProvider
ctrl *gomock.Controller
clientProvider *targetmocks.MockClientProvider
cfg *config.Config
gardenClient client.Client
testShootUnscheduled *gardencorev1beta1.Shoot
testShootAws *gardencorev1beta1.Shoot
testShootGCP *gardencorev1beta1.Shoot
)

BeforeEach(func() {
cfg = &config.Config{
LinkKubeconfig: pointer.Bool(false),
Gardens: []config.Garden{{
Name: gardenName,
}},
}

seedAws := "aws"
seedGcp := "gcp"
brokenShoot := "brokenShoot"

testShootUnscheduled = &gardencorev1beta1.Shoot{
ObjectMeta: metav1.ObjectMeta{Name: brokenShoot},
Spec: gardencorev1beta1.ShootSpec{
SeedName: nil,
},
}

testShootAws = &gardencorev1beta1.Shoot{
ObjectMeta: metav1.ObjectMeta{Name: seedAws},
Spec: gardencorev1beta1.ShootSpec{
SeedName: &seedAws,
},
}

testShootGCP = &gardencorev1beta1.Shoot{
ObjectMeta: metav1.ObjectMeta{Name: seedGcp},
Spec: gardencorev1beta1.ShootSpec{
SeedName: &seedGcp,
},
}

streams, _, out, _ = util.NewTestIOStreams()

ctrl = gomock.NewController(GinkgoT())

clientProvider = targetmocks.NewMockClientProvider(ctrl)
targetProvider = internalfake.NewFakeTargetProvider(target.NewTarget(gardenName, "", "", ""))

factory = internalfake.NewFakeFactory(cfg, nil, clientProvider, targetProvider)
})

JustBeforeEach(func() {
clientConfig, err := cfg.ClientConfig(gardenName)
Expect(err).ToNot(HaveOccurred())
clientProvider.EXPECT().FromClientConfig(gomock.Eq(clientConfig)).Return(gardenClient, nil).AnyTimes()
})

AfterEach(func() {
ctrl.Finish()
})

Describe("RunE", func() {
BeforeEach(func() {
gardenClient = internalfake.NewClientWithObjects(
testShootUnscheduled,
testShootAws,
testShootGCP,
)
})

It("should print info information", func() {
o := cmdinfo.NewInfoOptions(streams)
cmd := cmdinfo.NewCmdInfo(factory, o)

Expect(cmd.RunE(cmd, nil)).To(Succeed())
Expect(out.String()).To(Equal("Garden: mygarden\nSeed Total Active Hibernated Allocatable Capacity\n---- ----- ------ ---------- ----------- --------\n---- ----- ------ ---------- ----------- --------\nTOTAL 3 2 0 - -\nUnscheduled 1\nUnscheduled List brokenShoot\n\n"))
})
})
})
137 changes: 137 additions & 0 deletions pkg/cmd/info/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
SPDX-FileCopyrightText: 2022 SAP SE or an SAP affiliate company and Gardener contributors

SPDX-License-Identifier: Apache-2.0
*/

package info

import (
"fmt"
"sort"
"strings"
"text/tabwriter"

"github.com/gardener/gardenctl-v2/internal/util"
"github.com/gardener/gardenctl-v2/pkg/cmd/base"
)

// InfoOptions is a struct to support Info command.
type Options struct {
base.Options
// Allocatable is the seed allocatable
Allocatable int64
// Capacity is the seed capacity
Capacity int64
}

// NewInfoOptions returns initialized Options.
func NewInfoOptions(ioStreams util.IOStreams) *Options {
return &Options{
Options: base.Options{
IOStreams: ioStreams,
},
}
}

// Run does the actual work of the command.
func (o *Options) Run(f util.Factory) error {
manager, err := f.Manager()
if err != nil {
return err
}

infoTarget, err := manager.CurrentTarget()
if err != nil {
return err
}

// create client for the garden cluster.
gardenClient, err := manager.GardenClient(infoTarget.GardenName())
if err != nil {
return err
}

shootList, err := gardenClient.ListShoots(f.Context(), infoTarget.WithShootName("").AsListOption())
if err != nil {
return err
}

seedList, err := gardenClient.ListSeeds(f.Context(), infoTarget.WithSeedName("").AsListOption())
if err != nil {
return err
}

var (
unscheduled = 0
hibernatedShootsCount = 0
totalShootsCountPerSeed = make(map[string]int)
hibernatedShootsCountPerSeed = make(map[string]int)
unscheduledList = make([]string, 0)
infoOptions = make(map[string]Options)
valAllocatable int64
valCapacity int64
)

for _, seed := range seedList.Items {
allocatable := seed.Status.Allocatable["shoots"]
capacity := seed.Status.Capacity["shoots"]

if v, ok := allocatable.AsInt64(); ok {
valAllocatable = v
} else {
return fmt.Errorf("allocatable conversion is not possible")
}

if v, ok := capacity.AsInt64(); ok {
valCapacity = v
} else {
return fmt.Errorf("capacity conversion is not possible")
}

infoOptions[seed.Name] = Options{Allocatable: valAllocatable, Capacity: valCapacity}
}

for _, shoot := range shootList.Items {
if shoot.Spec.SeedName == nil {
// unscheduledList usually list pending clusters during creation
unscheduledList = append(unscheduledList, shoot.Name)
unscheduled++

continue
}
totalShootsCountPerSeed[*shoot.Spec.SeedName]++

if shoot.Status.IsHibernated {
hibernatedShootsCountPerSeed[*shoot.Spec.SeedName]++
hibernatedShootsCount++
}
}

var sortedSeeds []string
for seed := range totalShootsCountPerSeed {
sortedSeeds = append(sortedSeeds, seed)
}

sort.Strings(sortedSeeds)
fmt.Fprintf(o.IOStreams.Out, "Garden: %s\n", infoTarget.GardenName())

w := tabwriter.NewWriter(o.IOStreams.Out, 6, 0, 20, ' ', 0)
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", "Seed", "Total", "Active", "Hibernated", "Allocatable", "Capacity")
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", "----", "-----", "------", "----------", "-----------", "--------")

for _, seed := range sortedSeeds {
if v, found := infoOptions[seed]; found {
fmt.Fprintf(w, "%s\t%d\t%d\t%d\t%d\t%d\n", seed, totalShootsCountPerSeed[seed], totalShootsCountPerSeed[seed]-hibernatedShootsCountPerSeed[seed], hibernatedShootsCountPerSeed[seed], v.Allocatable, v.Capacity)
}
}

fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", "----", "-----", "------", "----------", "-----------", "--------")
fmt.Fprintf(w, "%s\t%d\t%d\t%d\t%s\t%s\n", "TOTAL", len(shootList.Items), len(shootList.Items)-hibernatedShootsCount-unscheduled, hibernatedShootsCount, "-", "-")
fmt.Fprintf(w, "%s\t%d\n", "Unscheduled", unscheduled)
fmt.Fprintf(w, "%s\t%s\n", "Unscheduled List", strings.Join(unscheduledList, ","))
fmt.Fprintln(w)
w.Flush()

return nil
}
2 changes: 1 addition & 1 deletion pkg/target/mocks/mock_manager.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.