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

mantle: Expand openstack gc to keypairs #3985

Merged
merged 1 commit into from
Dec 5, 2024
Merged
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
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
}
Loading