Skip to content

Instantly share code, notes, and snippets.

@alexrudd
Created April 21, 2022 19:38
Show Gist options
  • Save alexrudd/0cba3be2997a43adf00789cc2f4f01fa to your computer and use it in GitHub Desktop.
Save alexrudd/0cba3be2997a43adf00789cc2f4f01fa to your computer and use it in GitHub Desktop.
HoneyComb delete old columns
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"time"
)
type column struct {
ID string `json:"id"`
KeyName string `json:"key_name"`
Hidden bool `json:"hidden"`
Description string `json:"description"`
LastWritten time.Time `json:"last_written"`
Type string `json:"type"`
}
func main() {
var (
dataset = flag.String("dataset", "", "The honeycomb dataset to target")
apiKey = flag.String("api-key", "", "The honeycomb API key")
deletionAge = flag.Duration("deletion-age", 60*24*time.Hour, "Columns older than this age are deleted")
ctx = context.Background()
)
flag.Parse()
cols, err := getAllColumns(ctx, *apiKey, *dataset)
if err != nil {
log.Fatal(err)
}
log.Printf("found %d columns", len(cols))
for _, col := range cols {
if time.Since(col.LastWritten) > *deletionAge {
log.Printf("deleting column %s", col.KeyName)
deleteColumn(ctx, *apiKey, *dataset, col.ID)
}
}
}
func getAllColumns(ctx context.Context, apiKey, dataset string) ([]column, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://api.honeycomb.io/1/columns/%s", dataset), nil)
if err != nil {
return nil, fmt.Errorf("building column request: %w", err)
}
req.Header.Add("X-Honeycomb-Team", apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("requesting columns: %w", err)
} else if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("requesting columns: %s", resp.Status)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
columns := []column{}
err = json.Unmarshal(data, &columns)
if err != nil {
return nil, fmt.Errorf("unmarshalling data: %w", err)
}
return columns, nil
}
func deleteColumn(ctx context.Context, apiKey, dataset, id string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, fmt.Sprintf("https://api.honeycomb.io/1/columns/%s/%s", dataset, id), nil)
if err != nil {
return fmt.Errorf("building column request: %w", err)
}
req.Header.Add("X-Honeycomb-Team", apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("deleting column: %w", err)
} else if resp.StatusCode != http.StatusOK {
return fmt.Errorf("deleting column: %s", resp.Status)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment