Skip to content

Commit

Permalink
Added changes for deletion of sshKey/sshKeys
Browse files Browse the repository at this point in the history
  • Loading branch information
bkhadars committed Nov 23, 2021
1 parent 31ef17c commit 1160e5b
Show file tree
Hide file tree
Showing 5 changed files with 195 additions and 0 deletions.
81 changes: 81 additions & 0 deletions cmd/purge/keys/keys.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2021 IBM Corp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package keys

import (
"fmt"

"github.com/spf13/cobra"
"k8s.io/klog/v2"

"github.com/ppc64le-cloud/pvsadm/pkg"
"github.com/ppc64le-cloud/pvsadm/pkg/client"
"github.com/ppc64le-cloud/pvsadm/pkg/utils"
)

const deletePromptMessage = "Deleting all the above ssh key/key's, Do you really want to continue?"

var Cmd = &cobra.Command{
Use: "keys",
Short: "Delete PowerVS ssh key/keys",
Long: `Delete PowerVS ssh key/keys matching regex
pvsadm purge --help for information
`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if pkg.Options.Expr == "" {
return fmt.Errorf("--regexp is required and shouldn't be empty string")
}

return nil
},

RunE: func(cmd *cobra.Command, args []string) error {
opt := pkg.Options

c, err := client.NewClientWithEnv(opt.APIKey, opt.Environment, opt.Debug)
if err != nil {
klog.Errorf("failed to create a session with IBM cloud: %v", err)
return err
}

pvmclient, err := client.NewPVMClientWithEnv(c, opt.InstanceID, opt.InstanceName, opt.Environment)
if err != nil {
return err
}

keys, err := pvmclient.KeyClient.GetAllPurgeable(pkg.Options.Before, pkg.Options.Since, pkg.Options.Expr)
if err != nil {
return fmt.Errorf("failed to get the ssh keys, err: %v", err)
}

klog.Infof("keys matched are %s", keys)
if len(keys) != 0 {
if opt.NoPrompt || utils.AskConfirmation(deletePromptMessage) {
for _, key := range keys {
err = pvmclient.KeyClient.Delete(key)
if err != nil {
if opt.IgnoreErrors {
klog.Infof("error occurred while deleting the key: %v", err)
} else {
return fmt.Errorf("failed to delete a key, err: %v", err)
}
}
klog.Infof("Successfully deleted a key, id: %s", key)
}
}
}
return nil
},
}
8 changes: 8 additions & 0 deletions cmd/purge/purge.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package purge
import (
"fmt"
"github.com/ppc64le-cloud/pvsadm/cmd/purge/images"
"github.com/ppc64le-cloud/pvsadm/cmd/purge/keys"
"github.com/ppc64le-cloud/pvsadm/cmd/purge/networks"
"github.com/ppc64le-cloud/pvsadm/cmd/purge/vms"
"github.com/ppc64le-cloud/pvsadm/cmd/purge/volumes"
Expand Down Expand Up @@ -57,6 +58,12 @@ Examples:
# List the purgeable candidate virtual machines and exit without deleting
pvsadm purge vms --instance-name upstream-core --dry-run
# Delete all the ssh keys which are created before 12hrs
pvsadm purge keys --instance-name upstream-core --before 12h --regexp "^rdr-.*"
# Delete all the ssh keys starts with rdr-
pvsadm purge keys --instance-name upstream-core --regexp "^rdr-.*"
`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Code block to execute the strict check mentioned in the rootcmd for the environment.
Expand Down Expand Up @@ -84,6 +91,7 @@ func init() {
Cmd.AddCommand(vms.Cmd)
Cmd.AddCommand(networks.Cmd)
Cmd.AddCommand(volumes.Cmd)
Cmd.AddCommand(keys.Cmd)
Cmd.PersistentFlags().StringVarP(&pkg.Options.InstanceID, "instance-id", "i", "", "Instance ID of the PowerVS instance")
Cmd.PersistentFlags().StringVarP(&pkg.Options.InstanceName, "instance-name", "n", "", "Instance name of the PowerVS")
Cmd.PersistentFlags().BoolVar(&pkg.Options.DryRun, "dry-run", false, "dry run the action and don't delete the actual resources")
Expand Down
92 changes: 92 additions & 0 deletions pkg/client/key/key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright 2021 IBM Corp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package key

import (
"fmt"
"regexp"
"time"

"github.com/ppc64le-cloud/pvsadm/pkg"

"github.com/IBM-Cloud/power-go-client/clients/instance"
"github.com/IBM-Cloud/power-go-client/errors"
"github.com/IBM-Cloud/power-go-client/helpers"
"github.com/IBM-Cloud/power-go-client/ibmpisession"
"github.com/IBM-Cloud/power-go-client/power/client/p_cloud_tenants_ssh_keys"
"github.com/IBM-Cloud/power-go-client/power/models"
)

type Client struct {
session *ibmpisession.IBMPISession
client *instance.IBMPIKeyClient
instanceID string
}

func NewClient(sess *ibmpisession.IBMPISession, powerinstanceid string) *Client {
c := &Client{
session: sess,
instanceID: powerinstanceid,
}
c.client = instance.NewIBMPIKeyClient(sess, powerinstanceid)
return c
}

func (c *Client) Get(id string) (*models.SSHKey, error) {
return c.client.Get(id, c.instanceID)
}

func (c *Client) Create(name, sshKey string) (*models.SSHKey, *models.SSHKey, error) {
return c.client.Create(name, sshKey, c.instanceID)
}

func (c *Client) Delete(id string) error {
return c.client.Delete(id, c.instanceID)
}

// Get Keys...
//TODO:Replace Getall function with upstream code
func (c *Client) GetAll() (*models.SSHKeys, error) {

var tenantid = c.session.UserAccount
params := p_cloud_tenants_ssh_keys.NewPcloudTenantsSshkeysGetallParamsWithTimeout(helpers.PIGetTimeOut).WithTenantID(tenantid)
resp, err := c.session.Power.PCloudTenantsSSHKeys.PcloudTenantsSshkeysGetall(params, ibmpisession.NewAuth(c.session, c.instanceID))

if err != nil || resp == nil || resp.Payload == nil {
return nil, fmt.Errorf(errors.GetPIKeyOperationFailed, c.instanceID, err)
}
return resp.Payload, nil
}

func (c *Client) GetAllPurgeable(before, since time.Duration, expr string) ([]string, error) {
keys, err := c.GetAll()
if err != nil {
return nil, fmt.Errorf("failed to get the list of instances: %v", err)
}

var keysMatched []string
r, _ := regexp.Compile(expr)

for _, key := range keys.SSHKeys {
if !r.MatchString(*key.Name) {
continue
}
if !pkg.IsPurgeable(time.Time(*key.CreationDate), before, since) {
continue
}
keysMatched = append(keysMatched, *key.Name)
}
return keysMatched, nil
}
3 changes: 3 additions & 0 deletions pkg/client/pvmclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/ppc64le-cloud/pvsadm/pkg/client/events"
"github.com/ppc64le-cloud/pvsadm/pkg/client/image"
"github.com/ppc64le-cloud/pvsadm/pkg/client/instance"
"github.com/ppc64le-cloud/pvsadm/pkg/client/key"
"github.com/ppc64le-cloud/pvsadm/pkg/client/network"
"github.com/ppc64le-cloud/pvsadm/pkg/client/volume"
)
Expand All @@ -44,6 +45,7 @@ type PVMClient struct {
VolumeClient *volume.Client
NetworkClient *network.Client
EventsClient *events.Client
KeyClient *key.Client
}

func NewPVMClient(c *Client, instanceID, instanceName, ep string) (*PVMClient, error) {
Expand Down Expand Up @@ -95,5 +97,6 @@ func NewPVMClient(c *Client, instanceID, instanceName, ep string) (*PVMClient, e
pvmclient.InstanceClient = instance.NewClient(pvmclient.PISession, instanceID)
pvmclient.NetworkClient = network.NewClient(pvmclient.PISession, instanceID)
pvmclient.EventsClient = events.NewClient(pvmclient.PISession, instanceID)
pvmclient.KeyClient = key.NewClient(pvmclient.PISession, instanceID)
return pvmclient, nil
}
11 changes: 11 additions & 0 deletions pkg/utils/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,14 @@ func ReadUserInput(message string) string {
survey.AskOne(prompt, &name, survey.WithValidator(survey.Required))
return name
}

func MultiSelect(msg string, input []string) []string {
selected := []string{}
prompt := &survey.MultiSelect{
Message: msg,
Options: input,
}

survey.AskOne(prompt, &selected)
return selected
}

0 comments on commit 1160e5b

Please sign in to comment.