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

feat: Added retention command #184

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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: 2 additions & 0 deletions cmd/harbor/root/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/goharbor/harbor-cli/cmd/harbor/root/project"
"github.com/goharbor/harbor-cli/cmd/harbor/root/registry"
repositry "github.com/goharbor/harbor-cli/cmd/harbor/root/repository"
"github.com/goharbor/harbor-cli/cmd/harbor/root/retention"
"github.com/goharbor/harbor-cli/cmd/harbor/root/user"
"github.com/goharbor/harbor-cli/pkg/utils"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -109,6 +110,7 @@ harbor help
repositry.Repository(),
user.User(),
artifact.Artifact(),
retention.Retention(),
)

return root
Expand Down
21 changes: 21 additions & 0 deletions cmd/harbor/root/retention/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package retention

import (
"github.com/spf13/cobra"
)

func Retention() *cobra.Command {
cmd := &cobra.Command{
Use: "retention",
Short: "Manage retention rule in the project",
Long: `Manage retention rules in the project in Harbor`,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can use the Long explanation to explain what does this command do.
Since retention is a TAG RETENTION policy, we should communicate this well to the user.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also mention, "user can only create 15 tag retention rules per project".

Example: `harbor retention create`,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some example usecases here would be beneficial.

}
cmd.AddCommand(
CreateRetentionCommand(),
ListExecutionRetentionCommand(),
DeleteRetentionCommand(),
)

return cmd
}
70 changes: 70 additions & 0 deletions cmd/harbor/root/retention/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package retention

import (
"github.com/goharbor/harbor-cli/pkg/api"
"github.com/goharbor/harbor-cli/pkg/prompt"
"github.com/goharbor/harbor-cli/pkg/views/retention/create"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

func CreateRetentionCommand() *cobra.Command {
var opts create.CreateView

cmd := &cobra.Command{
Use: "create",
Short: "create retention tag rule",
Long: "create retention tag rule to the project in harbor",
Example: "harbor retention create",
Run: func(cmd *cobra.Command, args []string) {
var err error
createView := &create.CreateView{
ScopeSelectors: create.RetentionSelector{
Decoration: opts.ScopeSelectors.Decoration,
Pattern: opts.ScopeSelectors.Pattern,
},
TagSelectors: create.RetentionSelector{
Decoration: opts.TagSelectors.Decoration,
Pattern: opts.TagSelectors.Pattern,
Extras: opts.TagSelectors.Extras,
},
Scope: create.RetentionPolicyScope{
Level: opts.Scope.Level,
Ref: opts.Scope.Ref,
},
Template: opts.Template,
Params: opts.Params,
Action: opts.Action,
Algorithm: opts.Algorithm,
}

projectId := int32(prompt.GetProjectIDFromUser())
err = createRetentionView(createView,projectId)

if err != nil {
log.Errorf("failed to create retention tag rule: %v", err)
}

},
}

flags := cmd.Flags()
flags.StringVarP(&opts.ScopeSelectors.Decoration, "repodecoration", "", "", "repository which either apply or exclude from the rule")
flags.StringVarP(&opts.ScopeSelectors.Pattern, "repolist", "", "", "list of repository to which to either apply or exclude from the rule")
flags.StringVarP(&opts.TagSelectors.Decoration, "tagdecoration", "", "", "tags which either apply or exclude from the rule")
flags.StringVarP(&opts.TagSelectors.Pattern, "taglist", "", "", "list of tags to which to either apply or exclude from the rule")
flags.StringVarP(&opts.Scope.Level,"level","","project","scope of retention policy")
flags.StringVarP(&opts.Action,"action","","retain","Action of the retention policy")
flags.StringVarP(&opts.Algorithm,"algorithm","","or","Algorithm of retention policy")

return cmd
}

func createRetentionView(createView *create.CreateView,projectId int32) error {
if createView == nil {
createView = &create.CreateView{}
}

create.CreateRetentionView(createView)
return api.CreateRetention(*createView,projectId)
}
42 changes: 42 additions & 0 deletions cmd/harbor/root/retention/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package retention

import (
"fmt"
"strconv"

"github.com/goharbor/harbor-cli/pkg/api"
"github.com/goharbor/harbor-cli/pkg/prompt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

func DeleteRetentionCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "delete",
Short: "delete retention rule",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var err error
var retentionId int
var strretenId string
if len(args) > 0 {
retentionId,_ = strconv.Atoi(args[0])
err = api.DeleteRetention(int64(retentionId))
} else {
projectId := fmt.Sprintf("%d",prompt.GetProjectIDFromUser())
strretenId,err = api.GetRetentionId(projectId)
if err != nil {
log.Fatal(err)
}
retentionId,_ = strconv.Atoi(strretenId)
err = api.DeleteRetention(int64(retentionId))
}
if err != nil {
log.Errorf("failed to delete retention rule: %v", err)
}
},
}

return cmd
}

56 changes: 56 additions & 0 deletions cmd/harbor/root/retention/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package retention

import (
"fmt"
"strconv"

"github.com/goharbor/go-client/pkg/sdk/v2.0/client/retention"
"github.com/goharbor/harbor-cli/pkg/api"
"github.com/goharbor/harbor-cli/pkg/prompt"
"github.com/goharbor/harbor-cli/pkg/utils"
"github.com/goharbor/harbor-cli/pkg/views/retention/list"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

func ListExecutionRetentionCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list retention execution of the project",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an absolute wrong approach here.

As an user I would expect

./harbor project retention list

to return me the list of retention rules that I made. Instead of retention executions.

FIX THIS.

Comment on lines +19 to +20
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is absolute wrong approach here.

As an user I would expect

./harbor tag retention list

to return me the list of retention rules that I made. Instead of retention executions.

FIX THIS.

Args: cobra.MaximumNArgs(1),
Example: `harbor retention list [retentionid]`,
Run: func(cmd *cobra.Command, args []string) {
var err error
var resp retention.ListRetentionExecutionsOK
var retentionID int
var strretenId string
if len(args) > 0 {
retentionID,_ = strconv.Atoi(args[0])
resp, err = api.ListRetention(int32(retentionID))
} else {
projectId := fmt.Sprintf("%d",prompt.GetProjectIDFromUser())
strretenId,err = api.GetRetentionId(projectId)
if err != nil {
log.Fatal(err)
}
retentionID,_ := strconv.Atoi(strretenId)
resp, err = api.ListRetention(int32(retentionID))
}

if err != nil {
log.Errorf("failed to list retention execution: %v", err)
}
FormatFlag := viper.GetString("output-format")
if FormatFlag != "" {
utils.PrintPayloadInJSONFormat(resp)
return
}

list.ListRetentionRules(resp.Payload)

},
}

return cmd
}
114 changes: 114 additions & 0 deletions pkg/api/retention_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package api

import (
"errors"
"strconv"

"github.com/goharbor/go-client/pkg/sdk/v2.0/client/project"
"github.com/goharbor/go-client/pkg/sdk/v2.0/client/retention"
"github.com/goharbor/go-client/pkg/sdk/v2.0/models"
"github.com/goharbor/harbor-cli/pkg/utils"
"github.com/goharbor/harbor-cli/pkg/views/retention/create"
log "github.com/sirupsen/logrus"
)

func CreateRetention(opts create.CreateView, projectId int32) error {
ctx, client, err := utils.ContextWithClient()
if err != nil {
return err
}

tagSelector := &models.RetentionSelector{
Decoration: opts.TagSelectors.Decoration,
Pattern: opts.TagSelectors.Pattern,
Extras: opts.TagSelectors.Extras,
}
scope := models.RetentionSelector{
Decoration: opts.ScopeSelectors.Decoration,
Pattern: opts.ScopeSelectors.Pattern,
}
scopeSelector := map[string][]models.RetentionSelector{
"repository": {
scope,
},
}
param := make(map[string] interface{})
if opts.Template == "always" {
param = nil
} else {
value, err := strconv.Atoi(opts.Params.Value)
if err != nil {
return err
}
param[opts.Template] = value
}

var rule []*models.RetentionRule
rule = append(rule, &models.RetentionRule{
Action: opts.Action,
ScopeSelectors: scopeSelector,
TagSelectors: []*models.RetentionSelector{tagSelector},
Template: opts.Template,
Params: param,
})

triggerSettings := map[string]string{
"cron": "",
}

_, err = client.Retention.CreateRetention(ctx, &retention.CreateRetentionParams{Policy: &models.RetentionPolicy{Scope: &models.RetentionPolicyScope{Level: opts.Scope.Level,Ref: int64(projectId)},Trigger: &models.RetentionRuleTrigger{Kind: models.ScheduleObjTypeSchedule,Settings: triggerSettings},Algorithm: opts.Algorithm,Rules: rule}})
if err != nil {
return err
}

log.Info("Added Tag Retention Rule")
return nil
}

func ListRetention(projectID int32)(retention.ListRetentionExecutionsOK,error){
ctx, client, err := utils.ContextWithClient()
if err != nil {
return retention.ListRetentionExecutionsOK{}, err
}
response,err := client.Retention.ListRetentionExecutions(ctx,&retention.ListRetentionExecutionsParams{ID: int64(projectID)})
if err != nil {
return retention.ListRetentionExecutionsOK{}, err
}

return *response, nil
}

func GetRetentionId(projectId string) (string,error) {
ctx, client, err := utils.ContextWithClient()
if err != nil {
return "",err
}

response, err := client.Project.GetProject(ctx, &project.GetProjectParams{ProjectNameOrID: projectId})
if err != nil {
log.Errorf("failed to get project: %v", err)
return "", err
}

if response.Payload.Metadata == nil || response.Payload.Metadata.RetentionID == nil {
return "", errors.New("no retention policy present for the project")
}
retentionid := *response.Payload.Metadata.RetentionID

return retentionid,nil
}

func DeleteRetention(RetentionID int64) error{
ctx, client, err := utils.ContextWithClient()
if err != nil {
return err
}
_, err = client.Retention.DeleteRetention(ctx,&retention.DeleteRetentionParams{ID: RetentionID})
if err != nil {
return err
}

log.Info("retention rule deleted successfully")

return nil
}
11 changes: 11 additions & 0 deletions pkg/prompt/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ func GetProjectNameFromUser() string {
return <-projectName
}

func GetProjectIDFromUser() int32 {
projectId := make(chan int32)
go func() {
response, _ := api.ListProject()
pview.ProjectIdList(response.Payload, projectId)

}()

return <-projectId
}

func GetRepoNameFromUser(projectName string) string {
repositoryName := make(chan string)

Expand Down
23 changes: 23 additions & 0 deletions pkg/views/project/select/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,26 @@ func ProjectList(project []*models.Project, choice chan<- string) {
}

}

func ProjectIdList(project []*models.Project, choice chan<- int32) {
itemsList := make([]list.Item, len(project))
items := map[string]int32{}
for i, p := range project {
items[p.Name] = p.ProjectID
itemsList[i] = selection.Item(p.Name)
}

m := selection.NewModel(itemsList, "Project")

p, err := tea.NewProgram(m, tea.WithAltScreen()).Run()

if err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}

if p, ok := p.(selection.Model); ok {
choice <- items[p.Choice]
}

}
Loading
Loading