Skip to content

Commit

Permalink
mantle: Expand openstack gc to keypairs
Browse files Browse the repository at this point in the history
  • Loading branch information
gursewak1997 committed Dec 5, 2024
1 parent 49ce2cb commit 4b4b32d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion mantle/cmd/ore/openstack/gc.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var (
cmdGC = &cobra.Command{
Use: "gc",
Short: "GC resources in OpenStack",
Long: `Delete instances created over the given duration ago`,
Long: `Delete instances and keypairs created over the given duration ago`,
RunE: runGC,

SilenceUsage: true,
Expand Down
29 changes: 28 additions & 1 deletion mantle/platform/api/openstack/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,21 @@ func (a *API) DeleteKey(name string) error {
return keypairs.Delete(a.computeClient, name, nil).ExtractErr()
}

func (a *API) ListKeyPairs() ([]keypairs.KeyPair, error) {
opts := keypairs.ListOpts{}
// Retrieve all pages of keypairs
allPages, err := keypairs.List(a.computeClient, opts).AllPages()
if err != nil {
return nil, fmt.Errorf("failed to fetch keypair pages: %w", err)
}
// Extract keypairs from the pages
allKeyPairs, err := keypairs.ExtractKeyPairs(allPages)
if err != nil {
return nil, fmt.Errorf("failed to extract keypairs: %w", err)
}
return allKeyPairs, nil
}

func (a *API) listServersWithMetadata(metadata map[string]string) ([]servers.Server, error) {
pager := servers.List(a.computeClient, servers.ListOpts{})

Expand Down Expand Up @@ -667,7 +682,7 @@ func (a *API) listServersWithMetadata(metadata map[string]string) ([]servers.Ser

func (a *API) GC(gracePeriod time.Duration) error {
threshold := time.Now().Add(-gracePeriod)

// Clean up servers
servers, err := a.listServersWithMetadata(map[string]string{
"CreatedBy": "mantle",
})
Expand All @@ -683,5 +698,17 @@ func (a *API) GC(gracePeriod time.Duration) error {
return fmt.Errorf("couldn't delete server %s: %v", server.ID, err)
}
}
// Clean up keypairs
keypairs, err := a.ListKeyPairs()
if err != nil {
return err
}
for _, keypair := range keypairs {
if strings.HasPrefix(keypair.Name, "kola-") {
if err := a.DeleteKey(keypair.Name); err != nil {
return fmt.Errorf("couldn't delete keypair %s: %v", keypair.Name, err)
}
}
}
return nil
}

0 comments on commit 4b4b32d

Please sign in to comment.