68 lines
1.8 KiB
Go
68 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
|
|
"github.com/alecthomas/kong"
|
|
"github.com/apex/log"
|
|
"github.com/apex/log/handlers/json"
|
|
|
|
"gitlab.com/unboundsoftware/gitlab-cleanup-handler/gitlab"
|
|
"gitlab.com/unboundsoftware/gitlab-cleanup-handler/kube"
|
|
)
|
|
|
|
type CLI struct {
|
|
Namespaces []string `name:"namespaces" env:"NAMESPACES" help:"Comma-separated list of namespaces to check" required:"true"`
|
|
GitlabToken string `name:"gitlab-token" env:"GITLAB_TOKEN" help:"API token to use for communication with Gitlab" required:"true"`
|
|
}
|
|
|
|
var cli CLI
|
|
|
|
func main() {
|
|
_ = kong.Parse(&cli)
|
|
log.SetHandler(json.New(os.Stdout))
|
|
logger := log.WithField("service", "gitlab-cleanup-handler")
|
|
|
|
var kubeClient *kube.Client
|
|
if kubecfg, exists := os.LookupEnv("KUBECONFIG"); exists {
|
|
kubeClient = kube.New(kube.WithKubeConfigProvider(kubecfg))
|
|
} else {
|
|
kubeClient = kube.New()
|
|
}
|
|
gitlabClient := gitlab.New(cli.GitlabToken)
|
|
if err := handle(cli, logger, kubeClient, gitlabClient); err != nil {
|
|
logger.WithError(err).Error("handler")
|
|
}
|
|
}
|
|
|
|
type KubeClient interface {
|
|
GetImages(ctx context.Context, logger log.Interface, namespaces []string) (map[string][]string, error)
|
|
}
|
|
|
|
type GitlabClient interface {
|
|
GetTags(image string) ([]gitlab.Tag, error)
|
|
UpdateCleanupPolicy(project string, versions []string) error
|
|
}
|
|
|
|
func handle(cli CLI, logger log.Interface, kubeClient KubeClient, gitlabClient GitlabClient) error {
|
|
images, err := kubeClient.GetImages(context.Background(), logger, cli.Namespaces)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for image, versions := range images {
|
|
tags, err := gitlabClient.GetTags(image)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tagVersions := make([]string, len(tags))
|
|
for i, tag := range tags {
|
|
tagVersions[i] = tag.Name
|
|
}
|
|
if err := gitlabClient.UpdateCleanupPolicy(image, append(versions, tagVersions...)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|