update golang version (#21014)

* update golang version

to golang v1.23.2

Signed-off-by: wang yan <wangyan@vmware.com>
This commit is contained in:
Wang Yan 2024-10-10 13:36:18 +08:00 committed by GitHub
parent f6eec371d7
commit de281220b5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
252 changed files with 536 additions and 534 deletions

View File

@ -41,10 +41,10 @@ jobs:
- ubuntu-latest - ubuntu-latest
timeout-minutes: 100 timeout-minutes: 100
steps: steps:
- name: Set up Go 1.22 - name: Set up Go 1.23
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.22.3 go-version: 1.23.2
id: go id: go
- uses: actions/checkout@v3 - uses: actions/checkout@v3
with: with:
@ -102,10 +102,10 @@ jobs:
- ubuntu-latest - ubuntu-latest
timeout-minutes: 100 timeout-minutes: 100
steps: steps:
- name: Set up Go 1.22 - name: Set up Go 1.23
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.22.3 go-version: 1.23.2
id: go id: go
- uses: actions/checkout@v3 - uses: actions/checkout@v3
with: with:
@ -157,10 +157,10 @@ jobs:
- ubuntu-latest - ubuntu-latest
timeout-minutes: 100 timeout-minutes: 100
steps: steps:
- name: Set up Go 1.22 - name: Set up Go 1.23
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.22.3 go-version: 1.23.2
id: go id: go
- uses: actions/checkout@v3 - uses: actions/checkout@v3
with: with:
@ -212,10 +212,10 @@ jobs:
- ubuntu-latest - ubuntu-latest
timeout-minutes: 100 timeout-minutes: 100
steps: steps:
- name: Set up Go 1.22 - name: Set up Go 1.23
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.22.3 go-version: 1.23.2
id: go id: go
- uses: actions/checkout@v3 - uses: actions/checkout@v3
with: with:
@ -265,10 +265,10 @@ jobs:
- ubuntu-latest - ubuntu-latest
timeout-minutes: 100 timeout-minutes: 100
steps: steps:
- name: Set up Go 1.22 - name: Set up Go 1.23
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.22.3 go-version: 1.23.2
id: go id: go
- uses: actions/checkout@v3 - uses: actions/checkout@v3
with: with:

View File

@ -26,7 +26,7 @@ jobs:
- name: Set up Go 1.22 - name: Set up Go 1.22
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.22.3 go-version: 1.23.2
id: go id: go
- name: Setup Docker - name: Setup Docker
uses: docker-practice/actions-setup-docker@master uses: docker-practice/actions-setup-docker@master

View File

@ -28,7 +28,7 @@ jobs:
- name: Set up Go 1.21 - name: Set up Go 1.21
uses: actions/setup-go@v5 uses: actions/setup-go@v5
with: with:
go-version: 1.22.3 go-version: 1.23.2
id: go id: go
- uses: actions/checkout@v3 - uses: actions/checkout@v3
with: with:

View File

@ -143,7 +143,7 @@ The folder graph below shows the structure of the source code folder `harbor/src
Harbor backend is written in [Go](http://golang.org/). If you don't have a Harbor backend service development environment, please [set one up](https://golang.org/doc/install). Harbor backend is written in [Go](http://golang.org/). If you don't have a Harbor backend service development environment, please [set one up](https://golang.org/doc/install).
| Harbor | Requires Go | | Harbor | Requires Go |
|----------|---------------| |--------|-------------|
| 1.1 | 1.7.3 | | 1.1 | 1.7.3 |
| 1.2 | 1.7.3 | | 1.2 | 1.7.3 |
| 1.3 | 1.9.2 | | 1.3 | 1.9.2 |
@ -166,6 +166,7 @@ Harbor backend is written in [Go](http://golang.org/). If you don't have a Harbo
| 2.9 | 1.21.3 | | 2.9 | 1.21.3 |
| 2.10 | 1.21.8 | | 2.10 | 1.21.8 |
| 2.11 | 1.22.3 | | 2.11 | 1.22.3 |
| 2.12 | 1.23.2 |
Ensure your GOPATH and PATH have been configured in accordance with the Go environment instructions. Ensure your GOPATH and PATH have been configured in accordance with the Go environment instructions.

View File

@ -142,7 +142,7 @@ GOINSTALL=$(GOCMD) install
GOTEST=$(GOCMD) test GOTEST=$(GOCMD) test
GODEP=$(GOTEST) -i GODEP=$(GOTEST) -i
GOFMT=gofmt -w GOFMT=gofmt -w
GOBUILDIMAGE=golang:1.22.3 GOBUILDIMAGE=golang:1.23.2
GOBUILDPATHINCONTAINER=/harbor GOBUILDPATHINCONTAINER=/harbor
# go build # go build
@ -312,7 +312,7 @@ gen_apis: lint_apis
MOCKERY_IMAGENAME=$(IMAGENAMESPACE)/mockery MOCKERY_IMAGENAME=$(IMAGENAMESPACE)/mockery
MOCKERY_VERSION=v2.43.2 MOCKERY_VERSION=v2.46.2
MOCKERY=$(RUNCONTAINER)/src ${MOCKERY_IMAGENAME}:${MOCKERY_VERSION} MOCKERY=$(RUNCONTAINER)/src ${MOCKERY_IMAGENAME}:${MOCKERY_VERSION}
MOCKERY_IMAGE_BUILD_CMD=${DOCKERBUILD} -f ${TOOLSPATH}/mockery/Dockerfile --build-arg GOLANG=${GOBUILDIMAGE} --build-arg MOCKERY_VERSION=${MOCKERY_VERSION} -t ${MOCKERY_IMAGENAME}:$(MOCKERY_VERSION) . MOCKERY_IMAGE_BUILD_CMD=${DOCKERBUILD} -f ${TOOLSPATH}/mockery/Dockerfile --build-arg GOLANG=${GOBUILDIMAGE} --build-arg MOCKERY_VERSION=${MOCKERY_VERSION} -t ${MOCKERY_IMAGENAME}:$(MOCKERY_VERSION) .

View File

@ -1,4 +1,4 @@
FROM golang:1.22.3 FROM golang:1.23.2
ENV DISTRIBUTION_DIR /go/src/github.com/docker/distribution ENV DISTRIBUTION_DIR /go/src/github.com/docker/distribution
ENV BUILDTAGS include_oss include_gcs ENV BUILDTAGS include_oss include_gcs

View File

@ -1,4 +1,4 @@
FROM golang:1.22.3 FROM golang:1.23.2
ADD . /go/src/github.com/goharbor/harbor-scanner-trivy/ ADD . /go/src/github.com/goharbor/harbor-scanner-trivy/
WORKDIR /go/src/github.com/goharbor/harbor-scanner-trivy/ WORKDIR /go/src/github.com/goharbor/harbor-scanner-trivy/

View File

@ -19,7 +19,7 @@ TEMP=$(mktemp -d ${TMPDIR-/tmp}/trivy-adapter.XXXXXX)
git clone https://github.com/goharbor/harbor-scanner-trivy.git $TEMP git clone https://github.com/goharbor/harbor-scanner-trivy.git $TEMP
cd $TEMP; git checkout $VERSION; cd - cd $TEMP; git checkout $VERSION; cd -
echo "Building Trivy adapter binary based on golang:1.22.3..." echo "Building Trivy adapter binary based on golang:1.23.2..."
cp Dockerfile.binary $TEMP cp Dockerfile.binary $TEMP
docker build -f $TEMP/Dockerfile.binary -t trivy-adapter-golang $TEMP docker build -f $TEMP/Dockerfile.binary -t trivy-adapter-golang $TEMP

View File

@ -58,7 +58,7 @@ func NewBuilderForUser(user *models.User, ctl project.Controller) RBACUserBuilde
// NewBuilderForPolicies create a builder for the policies // NewBuilderForPolicies create a builder for the policies
func NewBuilderForPolicies(username string, policies []*types.Policy, func NewBuilderForPolicies(username string, policies []*types.Policy,
filters ...func(*proModels.Project, []*types.Policy) []*types.Policy) RBACUserBuilder { filters ...func(*proModels.Project, []*types.Policy) []*types.Policy) RBACUserBuilder {
return func(ctx context.Context, p *proModels.Project) types.RBACUser { return func(_ context.Context, p *proModels.Project) types.RBACUser {
for _, filter := range filters { for _, filter := range filters {
policies = filter(p, policies) policies = filter(p, policies)
} }

View File

@ -25,7 +25,7 @@ import (
// NewEvaluator create evaluator for the system // NewEvaluator create evaluator for the system
func NewEvaluator(username string, policies []*types.Policy) evaluator.Evaluator { func NewEvaluator(username string, policies []*types.Policy) evaluator.Evaluator {
return namespace.New(NamespaceKind, func(ctx context.Context, ns types.Namespace) evaluator.Evaluator { return namespace.New(NamespaceKind, func(_ context.Context, _ types.Namespace) evaluator.Evaluator {
return rbac.New(&rbacUser{ return rbac.New(&rbacUser{
username: username, username: username,
policies: policies, policies: policies,

View File

@ -106,7 +106,7 @@ func parseV1alpha1Icon(artifact *artifact.Artifact, manifest *v1.Manifest, reg r
switch contentType { switch contentType {
case GIF, PNG, JPEG: case GIF, PNG, JPEG:
default: default:
return errors.New(nil).WithCode(errors.BadRequestCode).WithMessage("unsupported content type: %s", contentType) return errors.New(nil).WithCode(errors.BadRequestCode).WithMessagef("unsupported content type: %s", contentType)
} }
artifact.Icon = iconDigest artifact.Icon = iconDigest
return nil return nil

View File

@ -307,7 +307,7 @@ func (c *controller) getByTag(ctx context.Context, repository, tag string, optio
} }
if len(tags) == 0 { if len(tags) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("artifact %s:%s not found", repository, tag) WithMessagef("artifact %s:%s not found", repository, tag)
} }
return c.Get(ctx, tags[0].ArtifactID, option) return c.Get(ctx, tags[0].ArtifactID, option)
} }

View File

@ -44,7 +44,7 @@ func (m *IndexProcessor) AbstractMetadata(_ context.Context, _ *artifact.Artifac
// AbstractAddition abstracts the addition of artifact // AbstractAddition abstracts the addition of artifact
func (m *IndexProcessor) AbstractAddition(_ context.Context, _ *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *IndexProcessor) AbstractAddition(_ context.Context, _ *artifact.Artifact, addition string) (*processor.Addition, error) {
return nil, errors.New(nil).WithCode(errors.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported", addition) WithMessagef("addition %s isn't supported", addition)
} }
// GetArtifactType returns the artifact type // GetArtifactType returns the artifact type

View File

@ -66,7 +66,7 @@ func (m *ManifestProcessor) AbstractMetadata(ctx context.Context, artifact *arti
// AbstractAddition abstracts the addition of artifact // AbstractAddition abstracts the addition of artifact
func (m *ManifestProcessor) AbstractAddition(_ context.Context, _ *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *ManifestProcessor) AbstractAddition(_ context.Context, _ *artifact.Artifact, addition string) (*processor.Addition, error) {
return nil, errors.New(nil).WithCode(errors.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported", addition) WithMessagef("addition %s isn't supported", addition)
} }
// GetArtifactType returns the artifact type // GetArtifactType returns the artifact type

View File

@ -61,7 +61,7 @@ type processor struct {
func (p *processor) AbstractAddition(_ context.Context, artifact *artifact.Artifact, addition string) (*ps.Addition, error) { func (p *processor) AbstractAddition(_ context.Context, artifact *artifact.Artifact, addition string) (*ps.Addition, error) {
if addition != AdditionTypeValues && addition != AdditionTypeReadme && addition != AdditionTypeDependencies { if addition != AdditionTypeValues && addition != AdditionTypeReadme && addition != AdditionTypeDependencies {
return nil, errors.New(nil).WithCode(errors.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported for %s", addition, ArtifactTypeChart) WithMessagef("addition %s isn't supported for %s", addition, ArtifactTypeChart)
} }
m, _, err := p.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest) m, _, err := p.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest)

View File

@ -132,5 +132,5 @@ func (d *defaultProcessor) AbstractAddition(_ context.Context, artifact *artifac
// It will be support in the future. // It will be support in the future.
// return error directly // return error directly
return nil, errors.New(nil).WithCode(errors.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("the processor for artifact %s not found, cannot get the addition", artifact.Type) WithMessagef("the processor for artifact %s not found, cannot get the addition", artifact.Type)
} }

View File

@ -52,7 +52,7 @@ func (m *manifestV1Processor) AbstractMetadata(_ context.Context, artifact *arti
func (m *manifestV1Processor) AbstractAddition(_ context.Context, _ *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *manifestV1Processor) AbstractAddition(_ context.Context, _ *artifact.Artifact, addition string) (*processor.Addition, error) {
return nil, errors.New(nil).WithCode(errors.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported for %s(manifest version 1)", addition, ArtifactTypeImage) WithMessagef("addition %s isn't supported for %s(manifest version 1)", addition, ArtifactTypeImage)
} }
func (m *manifestV1Processor) GetArtifactType(_ context.Context, _ *artifact.Artifact) string { func (m *manifestV1Processor) GetArtifactType(_ context.Context, _ *artifact.Artifact) string {

View File

@ -87,7 +87,7 @@ func (m *manifestV2Processor) AbstractMetadata(ctx context.Context, artifact *ar
func (m *manifestV2Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *manifestV2Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) {
if addition != AdditionTypeBuildHistory { if addition != AdditionTypeBuildHistory {
return nil, errors.New(nil).WithCode(errors.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported for %s(manifest version 2)", addition, ArtifactTypeImage) WithMessagef("addition %s isn't supported for %s(manifest version 2)", addition, ArtifactTypeImage)
} }
mani, _, err := m.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest) mani, _, err := m.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest)

View File

@ -103,7 +103,7 @@ func (m *Processor) AbstractMetadata(ctx context.Context, art *artifact.Artifact
func (m *Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) { func (m *Processor) AbstractAddition(ctx context.Context, artifact *artifact.Artifact, addition string) (*processor.Addition, error) {
if addition != AdditionTypeBuildHistory { if addition != AdditionTypeBuildHistory {
return nil, errors.New(nil).WithCode(errors.BadRequestCode). return nil, errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("addition %s isn't supported for %s(manifest version 2)", addition, ArtifactTypeWASM) WithMessagef("addition %s isn't supported for %s(manifest version 2)", addition, ArtifactTypeWASM)
} }
mani, _, err := m.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest) mani, _, err := m.RegCli.PullManifest(artifact.RepositoryName, artifact.Digest)

View File

@ -248,7 +248,7 @@ func (c *controller) Get(ctx context.Context, digest string, options ...Option)
if err != nil { if err != nil {
return nil, err return nil, err
} else if len(blobs) == 0 { } else if len(blobs) == 0 {
return nil, errors.NotFoundError(nil).WithMessage("blob %s not found", digest) return nil, errors.NotFoundError(nil).WithMessagef("blob %s not found", digest)
} }
return blobs[0], nil return blobs[0], nil
@ -363,7 +363,7 @@ func (c *controller) Touch(ctx context.Context, blob *blob.Blob) error {
return err return err
} }
if count == 0 { if count == 0 {
return errors.New(nil).WithMessage(fmt.Sprintf("no blob item is updated to StatusNone, id:%d, digest:%s", blob.ID, blob.Digest)).WithCode(errors.NotFoundCode) return errors.New(nil).WithMessagef("no blob item is updated to StatusNone, id:%d, digest:%s", blob.ID, blob.Digest).WithCode(errors.NotFoundCode)
} }
return nil return nil
} }
@ -375,7 +375,7 @@ func (c *controller) Fail(ctx context.Context, blob *blob.Blob) error {
return err return err
} }
if count == 0 { if count == 0 {
return errors.New(nil).WithMessage(fmt.Sprintf("no blob item is updated to StatusDeleteFailed, id:%d, digest:%s", blob.ID, blob.Digest)).WithCode(errors.NotFoundCode) return errors.New(nil).WithMessagef("no blob item is updated to StatusDeleteFailed, id:%d, digest:%s", blob.ID, blob.Digest).WithCode(errors.NotFoundCode)
} }
return nil return nil
} }

View File

@ -182,11 +182,11 @@ func verifyValueLengthCfg(_ context.Context, cfgs map[string]interface{}) error
// the cfgs is unmarshal from json string, the number type will be float64 // the cfgs is unmarshal from json string, the number type will be float64
if vf, ok := v.(float64); ok { if vf, ok := v.(float64); ok {
if vf <= 0 { if vf <= 0 {
return errors.BadRequestError(nil).WithMessage("the %s value must be positive", c) return errors.BadRequestError(nil).WithMessagef("the %s value must be positive", c)
} }
if int64(vf) > maxValue { if int64(vf) > maxValue {
return errors.BadRequestError(nil).WithMessage(fmt.Sprintf("the %s value is over the limit value: %d", c, maxValue)) return errors.BadRequestError(nil).WithMessagef("the %s value is over the limit value: %d", c, maxValue)
} }
} }
} }

View File

@ -139,7 +139,7 @@ func (c *controller) GetExecution(ctx context.Context, id int64) (*Execution, er
} }
if len(execs) == 0 { if len(execs) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("garbage collection execution %d not found", id) WithMessagef("garbage collection execution %d not found", id)
} }
return convertExecution(execs[0]), nil return convertExecution(execs[0]), nil
} }
@ -157,7 +157,7 @@ func (c *controller) GetTask(ctx context.Context, id int64) (*Task, error) {
} }
if len(tasks) == 0 { if len(tasks) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("garbage collection task %d not found", id) WithMessagef("garbage collection task %d not found", id)
} }
return convertTask(tasks[0]), nil return convertTask(tasks[0]), nil
} }

View File

@ -143,7 +143,7 @@ func (c *controller) Get(ctx context.Context, digest string) (*Icon, error) {
} }
if len(artifacts) == 0 { if len(artifacts) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("the icon %s not found", digest) WithMessagef("the icon %s not found", digest)
} }
_, iconFile, err = c.regCli.PullBlob(artifacts[0].RepositoryName, digest) _, iconFile, err = c.regCli.PullBlob(artifacts[0].RepositoryName, digest)
if err != nil { if err != nil {

View File

@ -135,20 +135,20 @@ func (c *controller) Create(ctx context.Context, projectNameOrID interface{}, re
if req.MemberUser.UserID > 0 { if req.MemberUser.UserID > 0 {
user, err := c.userManager.Get(ctx, req.MemberUser.UserID) user, err := c.userManager.Get(ctx, req.MemberUser.UserID)
if err != nil { if err != nil {
return 0, errors.BadRequestError(nil).WithMessage("Failed to get user %d: %v", req.MemberUser.UserID, err) return 0, errors.BadRequestError(nil).WithMessagef("Failed to get user %d: %v", req.MemberUser.UserID, err)
} }
if user == nil { if user == nil {
return 0, errors.BadRequestError(nil).WithMessage("User %d not found", req.MemberUser.UserID) return 0, errors.BadRequestError(nil).WithMessagef("User %d not found", req.MemberUser.UserID)
} }
member.EntityID = req.MemberUser.UserID member.EntityID = req.MemberUser.UserID
member.EntityType = common.UserMember member.EntityType = common.UserMember
} else if req.MemberGroup.ID > 0 { } else if req.MemberGroup.ID > 0 {
g, err := c.groupManager.Get(ctx, req.MemberGroup.ID) g, err := c.groupManager.Get(ctx, req.MemberGroup.ID)
if err != nil { if err != nil {
return 0, errors.BadRequestError(nil).WithMessage("Failed to get group %d: %v", req.MemberGroup.ID, err) return 0, errors.BadRequestError(nil).WithMessagef("Failed to get group %d: %v", req.MemberGroup.ID, err)
} }
if g == nil { if g == nil {
return 0, errors.BadRequestError(nil).WithMessage("Group %d not found", req.MemberGroup.ID) return 0, errors.BadRequestError(nil).WithMessagef("Group %d not found", req.MemberGroup.ID)
} }
member.EntityID = req.MemberGroup.ID member.EntityID = req.MemberGroup.ID
} else if len(req.MemberUser.Username) > 0 { } else if len(req.MemberUser.Username) > 0 {

View File

@ -219,7 +219,7 @@ func (c *controller) DeleteInstance(ctx context.Context, id int64) error {
if len(policies) > 0 { if len(policies) > 0 {
return errors.New(nil). return errors.New(nil).
WithCode(errors.PreconditionCode). WithCode(errors.PreconditionCode).
WithMessage("Provider [%s] cannot be deleted as some preheat policies are using it", ins.Name) WithMessagef("Provider [%s] cannot be deleted as some preheat policies are using it", ins.Name)
} }
return c.iManager.Delete(ctx, id) return c.iManager.Delete(ctx, id)
@ -246,7 +246,7 @@ func (c *controller) UpdateInstance(ctx context.Context, instance *providerModel
if len(policies) > 0 { if len(policies) > 0 {
return errors.New(nil). return errors.New(nil).
WithCode(errors.PreconditionCode). WithCode(errors.PreconditionCode).
WithMessage("Provider [%s] cannot be disabled as some preheat policies are using it", oldIns.Name) WithMessagef("Provider [%s] cannot be disabled as some preheat policies are using it", oldIns.Name)
} }
} }

View File

@ -349,7 +349,7 @@ func (c *controller) updateUsageWithRetry(ctx context.Context, reference, refere
options := []retry.Option{ options := []retry.Option{
retry.Timeout(defaultRetryTimeout), retry.Timeout(defaultRetryTimeout),
retry.Backoff(false), retry.Backoff(false),
retry.Callback(func(err error, sleep time.Duration) { retry.Callback(func(err error, _ time.Duration) {
log.G(ctx).Debugf("failed to update the quota usage for %s %s, error: %v", reference, referenceID, err) log.G(ctx).Debugf("failed to update the quota usage for %s %s, error: %v", reference, referenceID, err)
}), }),
} }
@ -488,7 +488,7 @@ func reserveResources(resources types.ResourceList) func(hardLimits, used types.
newUsed := types.Add(used, resources) newUsed := types.Add(used, resources)
if err := quota.IsSafe(hardLimits, used, newUsed, false); err != nil { if err := quota.IsSafe(hardLimits, used, newUsed, false); err != nil {
return nil, errors.DeniedError(err).WithMessage("Quota exceeded when processing the request of %v", err) return nil, errors.DeniedError(err).WithMessagef("Quota exceeded when processing the request of %v", err)
} }
return newUsed, nil return newUsed, nil
@ -496,7 +496,7 @@ func reserveResources(resources types.ResourceList) func(hardLimits, used types.
} }
func rollbackResources(resources types.ResourceList) func(hardLimits, used types.ResourceList) (types.ResourceList, error) { func rollbackResources(resources types.ResourceList) func(hardLimits, used types.ResourceList) (types.ResourceList, error) {
return func(hardLimits, used types.ResourceList) (types.ResourceList, error) { return func(_, used types.ResourceList) (types.ResourceList, error) {
newUsed := types.Subtract(used, resources) newUsed := types.Subtract(used, resources)
// ensure that new used is never negative // ensure that new used is never negative
if negativeUsed := types.IsNegative(newUsed); len(negativeUsed) > 0 { if negativeUsed := types.IsNegative(newUsed); len(negativeUsed) > 0 {

View File

@ -75,7 +75,7 @@ func getProjectsBatchFn(ctx context.Context, keys dataloader.Keys) []*dataloader
for _, projectID := range projectIDs { for _, projectID := range projectIDs {
project, ok := projectsMap[projectID] project, ok := projectsMap[projectID]
if !ok { if !ok {
err := errors.NotFoundError(nil).WithMessage("project %d not found", projectID) err := errors.NotFoundError(nil).WithMessagef("project %d not found", projectID)
return handleError(err) return handleError(err)
} }

View File

@ -136,7 +136,7 @@ func (c *controller) Delete(ctx context.Context, id int64) error {
return err return err
} }
if count > 0 { if count > 0 {
return errors.New(nil).WithCode(errors.PreconditionCode).WithMessage("the registry %d is referenced by replication policies, cannot delete it", id) return errors.New(nil).WithCode(errors.PreconditionCode).WithMessagef("the registry %d is referenced by replication policies, cannot delete it", id)
} }
// referenced by replication policy as destination registry // referenced by replication policy as destination registry
count, err = c.repMgr.Count(ctx, &q.Query{ count, err = c.repMgr.Count(ctx, &q.Query{
@ -148,7 +148,7 @@ func (c *controller) Delete(ctx context.Context, id int64) error {
return err return err
} }
if count > 0 { if count > 0 {
return errors.New(nil).WithCode(errors.PreconditionCode).WithMessage("the registry %d is referenced by replication policies, cannot delete it", id) return errors.New(nil).WithCode(errors.PreconditionCode).WithMessagef("the registry %d is referenced by replication policies, cannot delete it", id)
} }
// referenced by proxy cache project // referenced by proxy cache project
count, err = c.proMgr.Count(ctx, &q.Query{ count, err = c.proMgr.Count(ctx, &q.Query{
@ -160,7 +160,7 @@ func (c *controller) Delete(ctx context.Context, id int64) error {
return err return err
} }
if count > 0 { if count > 0 {
return errors.New(nil).WithCode(errors.PreconditionCode).WithMessage("the registry %d is referenced by proxy cache project, cannot delete it", id) return errors.New(nil).WithCode(errors.PreconditionCode).WithMessagef("the registry %d is referenced by proxy cache project, cannot delete it", id)
} }
return c.regMgr.Delete(ctx, id) return c.regMgr.Delete(ctx, id)

View File

@ -102,7 +102,7 @@ func (c *controller) Start(ctx context.Context, policy *replicationmodel.Policy,
logger := log.GetLogger(ctx) logger := log.GetLogger(ctx)
if !policy.Enabled { if !policy.Enabled {
return 0, errors.New(nil).WithCode(errors.PreconditionCode). return 0, errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the policy %d is disabled", policy.ID) WithMessagef("the policy %d is disabled", policy.ID)
} }
// create an execution record // create an execution record
extra := make(map[string]interface{}) extra := make(map[string]interface{})
@ -213,7 +213,7 @@ func (c *controller) GetExecution(ctx context.Context, id int64) (*Execution, er
} }
if len(execs) == 0 { if len(execs) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("replication execution %d not found", id) WithMessagef("replication execution %d not found", id)
} }
return convertExecution(execs[0]), nil return convertExecution(execs[0]), nil
} }
@ -250,7 +250,7 @@ func (c *controller) GetTask(ctx context.Context, id int64) (*Task, error) {
} }
if len(tasks) == 0 { if len(tasks) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("replication task %d not found", id) WithMessagef("replication task %d not found", id)
} }
return convertTask(tasks[0]), nil return convertTask(tasks[0]), nil
} }

View File

@ -1,4 +1,4 @@
// Code generated by mockery v2.43.2. DO NOT EDIT. // Code generated by mockery v2.46.2. DO NOT EDIT.
package flow package flow

View File

@ -1,4 +1,4 @@
// Code generated by mockery v2.43.2. DO NOT EDIT. // Code generated by mockery v2.46.2. DO NOT EDIT.
package flow package flow

View File

@ -203,7 +203,7 @@ func replaceNamespace(repository string, namespace string, replaceCount int8, ds
dstRepoPrefix = namespace dstRepoPrefix = namespace
case int(replaceCount) > srcLength-1: // invalid replace count case int(replaceCount) > srcLength-1: // invalid replace count
return "", errors.New(nil).WithCode(errors.BadRequestCode). return "", errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("the source repository %q contains only %d path components %v excepting the last one, but the destination namespace flattening level is %d", WithMessagef("the source repository %q contains only %d path components %v excepting the last one, but the destination namespace flattening level is %d",
repository, srcLength-1, srcRepoPathComponents[:srcLength-1], replaceCount) repository, srcLength-1, srcRepoPathComponents[:srcLength-1], replaceCount)
default: default:
dstRepoPrefix = namespace + "/" + strings.Join(srcRepoPathComponents[replaceCount:srcLength-1], "/") dstRepoPrefix = namespace + "/" + strings.Join(srcRepoPathComponents[replaceCount:srcLength-1], "/")
@ -216,12 +216,12 @@ func replaceNamespace(repository string, namespace string, replaceCount int8, ds
switch dstRepoComponentPathType { switch dstRepoComponentPathType {
case model.RepositoryPathComponentTypeOnlyTwo: case model.RepositoryPathComponentTypeOnlyTwo:
if dstLength != 2 { if dstLength != 2 {
return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessage("the destination repository %q contains %d path components %v, but the destination registry only supports 2", return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessagef("the destination repository %q contains %d path components %v, but the destination registry only supports 2",
dstRepo, dstLength, dstRepoPathComponents) dstRepo, dstLength, dstRepoPathComponents)
} }
case model.RepositoryPathComponentTypeAtLeastTwo: case model.RepositoryPathComponentTypeAtLeastTwo:
if dstLength < 2 { if dstLength < 2 {
return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessage("the destination repository %q contains only %d path components %v, but the destination registry requires at least 2", return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessagef("the destination repository %q contains only %d path components %v, but the destination registry requires at least 2",
dstRepo, dstLength, dstRepoPathComponents) dstRepo, dstLength, dstRepoPathComponents)
} }
} }

View File

@ -1,4 +1,4 @@
// Code generated by mockery v2.43.2. DO NOT EDIT. // Code generated by mockery v2.46.2. DO NOT EDIT.
package replication package replication

View File

@ -91,7 +91,7 @@ func (p *Policy) Validate() error {
if len(p.DestNamespace) > 0 { if len(p.DestNamespace) > 0 {
if !lib.RepositoryNameRe.MatchString(p.DestNamespace) { if !lib.RepositoryNameRe.MatchString(p.DestNamespace) {
return errors.New(nil).WithCode(errors.BadRequestCode). return errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid destination namespace: %s", p.DestNamespace) WithMessagef("invalid destination namespace: %s", p.DestNamespace)
} }
} }
@ -102,11 +102,11 @@ func (p *Policy) Validate() error {
case model.TriggerTypeScheduled: case model.TriggerTypeScheduled:
if p.Trigger.Settings == nil || len(p.Trigger.Settings.Cron) == 0 { if p.Trigger.Settings == nil || len(p.Trigger.Settings.Cron) == 0 {
return errors.New(nil).WithCode(errors.BadRequestCode). return errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("the cron string cannot be empty when the trigger type is %s", model.TriggerTypeScheduled) WithMessagef("the cron string cannot be empty when the trigger type is %s", model.TriggerTypeScheduled)
} }
if _, err := utils.CronParser().Parse(p.Trigger.Settings.Cron); err != nil { if _, err := utils.CronParser().Parse(p.Trigger.Settings.Cron); err != nil {
return errors.New(nil).WithCode(errors.BadRequestCode). return errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid cron string for scheduled trigger: %s", p.Trigger.Settings.Cron) WithMessagef("invalid cron string for scheduled trigger: %s", p.Trigger.Settings.Cron)
} }
cronParts := strings.Split(p.Trigger.Settings.Cron, " ") cronParts := strings.Split(p.Trigger.Settings.Cron, " ")
if cronParts[0] != "0" { if cronParts[0] != "0" {

View File

@ -36,8 +36,6 @@ import (
"github.com/goharbor/harbor/src/pkg/task" "github.com/goharbor/harbor/src/pkg/task"
) )
// go:generate mockery -name Controller -case snake
// Controller to handle the requests related with retention // Controller to handle the requests related with retention
type Controller interface { type Controller interface {
GetRetention(ctx context.Context, id int64) (*policy.Metadata, error) GetRetention(ctx context.Context, id int64) (*policy.Metadata, error)

View File

@ -243,12 +243,12 @@ func (bc *basicController) Scan(ctx context.Context, artifact *ar.Artifact, opti
// In case it does not exist // In case it does not exist
if r == nil { if r == nil {
return errors.PreconditionFailedError(nil).WithMessage("no available scanner for project: %d", artifact.ProjectID) return errors.PreconditionFailedError(nil).WithMessagef("no available scanner for project: %d", artifact.ProjectID)
} }
// Check if it is disabled // Check if it is disabled
if r.Disabled { if r.Disabled {
return errors.PreconditionFailedError(nil).WithMessage("scanner %s is deactivated", r.Name) return errors.PreconditionFailedError(nil).WithMessagef("scanner %s is deactivated", r.Name)
} }
artifacts, scannable, err := bc.collectScanningArtifacts(ctx, r, artifact) artifacts, scannable, err := bc.collectScanningArtifacts(ctx, r, artifact)
@ -266,7 +266,7 @@ func (bc *basicController) Scan(ctx context.Context, artifact *ar.Artifact, opti
// skip to return err for event related scan // skip to return err for event related scan
return nil return nil
} }
return errors.BadRequestError(nil).WithMessage("the configured scanner %s does not support scanning artifact with mime type %s", r.Name, artifact.ManifestMediaType) return errors.BadRequestError(nil).WithMessagef("the configured scanner %s does not support scanning artifact with mime type %s", r.Name, artifact.ManifestMediaType)
} }
var ( var (
@ -376,8 +376,7 @@ func (bc *basicController) Stop(ctx context.Context, artifact *ar.Artifact, capT
} }
if len(executions) == 0 { if len(executions) == 0 {
message := fmt.Sprintf("no scan job for artifact digest=%v", artifact.Digest) return errors.BadRequestError(nil).WithMessagef("no scan job for artifact digest=%v", artifact.Digest)
return errors.BadRequestError(nil).WithMessage(message)
} }
execution := executions[0] execution := executions[0]
return bc.execMgr.Stop(ctx, execution.ID) return bc.execMgr.Stop(ctx, execution.ID)
@ -590,7 +589,7 @@ func (bc *basicController) GetReport(ctx context.Context, artifact *ar.Artifact,
} }
if r == nil { if r == nil {
return nil, errors.NotFoundError(nil).WithMessage("no scanner registration configured for project: %d", artifact.ProjectID) return nil, errors.NotFoundError(nil).WithMessagef("no scanner registration configured for project: %d", artifact.ProjectID)
} }
artifacts, scannable, err := bc.collectScanningArtifacts(ctx, r, artifact) artifacts, scannable, err := bc.collectScanningArtifacts(ctx, r, artifact)
@ -599,7 +598,7 @@ func (bc *basicController) GetReport(ctx context.Context, artifact *ar.Artifact,
} }
if !scannable { if !scannable {
return nil, errors.NotFoundError(nil).WithMessage("report not found for %s@%s", artifact.RepositoryName, artifact.Digest) return nil, errors.NotFoundError(nil).WithMessagef("report not found for %s@%s", artifact.RepositoryName, artifact.Digest)
} }
groupReports := make([][]*scan.Report, len(artifacts)) groupReports := make([][]*scan.Report, len(artifacts))
@ -681,7 +680,7 @@ func (bc *basicController) GetScanLog(ctx context.Context, artifact *ar.Artifact
reportUUIDToTasks := map[string]*task.Task{} reportUUIDToTasks := map[string]*task.Task{}
for _, t := range tasks { for _, t := range tasks {
if !scanTaskForArtifacts(t, artifactMap) { if !scanTaskForArtifacts(t, artifactMap) {
return nil, errors.NotFoundError(nil).WithMessage("scan log with uuid: %s not found", uuid) return nil, errors.NotFoundError(nil).WithMessagef("scan log with uuid: %s not found", uuid)
} }
for _, reportUUID := range GetReportUUIDs(t.ExtraAttrs) { for _, reportUUID := range GetReportUUIDs(t.ExtraAttrs) {
reportUUIDToTasks[reportUUID] = t reportUUIDToTasks[reportUUID] = t
@ -1043,7 +1042,7 @@ func (bc *basicController) getScanTask(ctx context.Context, reportUUID string) (
} }
if len(tasks) == 0 { if len(tasks) == 0 {
return nil, errors.NotFoundError(nil).WithMessage("task for report %s not found", reportUUID) return nil, errors.NotFoundError(nil).WithMessagef("task for report %s not found", reportUUID)
} }
return tasks[0], nil return tasks[0], nil

View File

@ -98,7 +98,7 @@ func (bc *basicController) GetTotalOfRegistrations(ctx context.Context, query *q
// CreateRegistration ... // CreateRegistration ...
func (bc *basicController) CreateRegistration(ctx context.Context, registration *scanner.Registration) (string, error) { func (bc *basicController) CreateRegistration(ctx context.Context, registration *scanner.Registration) (string, error) {
if isReservedName(registration.Name) { if isReservedName(registration.Name) {
return "", errors.BadRequestError(nil).WithMessage(`name "%s" is reserved, please try a different name`, registration.Name) return "", errors.BadRequestError(nil).WithMessagef(`name "%s" is reserved, please try a different name`, registration.Name)
} }
// Check if the registration is available // Check if the registration is available
@ -168,7 +168,7 @@ func (bc *basicController) UpdateRegistration(ctx context.Context, registration
} }
if isReservedName(registration.Name) { if isReservedName(registration.Name) {
return errors.BadRequestError(nil).WithMessage(`name "%s" is reserved, please try a different name`, registration.Name) return errors.BadRequestError(nil).WithMessagef(`name "%s" is reserved, please try a different name`, registration.Name)
} }
return bc.manager.Update(ctx, registration) return bc.manager.Update(ctx, registration)
@ -343,7 +343,7 @@ func (bc *basicController) GetMetadata(ctx context.Context, registrationUUID str
} }
if r == nil { if r == nil {
return nil, errors.NotFoundError(nil).WithMessage("registration %s not found", registrationUUID) return nil, errors.NotFoundError(nil).WithMessagef("registration %s not found", registrationUUID)
} }
return bc.Ping(ctx, r) return bc.Ping(ctx, r)
@ -402,7 +402,7 @@ type MetadataResult struct {
func (m *MetadataResult) Unpack() (*v1.ScannerAdapterMetadata, error) { func (m *MetadataResult) Unpack() (*v1.ScannerAdapterMetadata, error) {
var err error var err error
if m.Error != "" { if m.Error != "" {
err = fmt.Errorf(m.Error) err = errors.New(nil).WithMessage(m.Error)
} }
return m.Metadata, err return m.Metadata, err

View File

@ -147,11 +147,11 @@ func (c *controller) attachTags(ctx context.Context, vuls []*secHubModel.Vulnera
} }
// get tags in the artifact list // get tags in the artifact list
var artifactIds []interface{} var artifactIDs []interface{}
for k := range artifactTagMap { for k := range artifactTagMap {
artifactIds = append(artifactIds, k) artifactIDs = append(artifactIDs, k)
} }
query := q.New(q.KeyWords{"artifact_id": q.NewOrList(artifactIds)}) query := q.New(q.KeyWords{"artifact_id": q.NewOrList(artifactIDs)})
tags, err := c.tagMgr.List(ctx, query) tags, err := c.tagMgr.List(ctx, query)
if err != nil { if err != nil {
return vuls, err return vuls, err

View File

@ -97,7 +97,7 @@ func (c *controller) Ensure(ctx context.Context, repositoryID, artifactID int64,
// existing tag must check the immutable status and signature // existing tag must check the immutable status and signature
if tag.Immutable { if tag.Immutable {
return 0, errors.New(nil).WithCode(errors.PreconditionCode). return 0, errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the tag %s configured as immutable, cannot be updated", tag.Name) WithMessagef("the tag %s configured as immutable, cannot be updated", tag.Name)
} }
// the tag exists under the repository, but it is attached to other artifact // the tag exists under the repository, but it is attached to other artifact
// update it to point to the provided artifact // update it to point to the provided artifact
@ -189,7 +189,7 @@ func (c *controller) Delete(ctx context.Context, id int64) (err error) {
} }
if tag.Immutable { if tag.Immutable {
return errors.New(nil).WithCode(errors.PreconditionCode). return errors.New(nil).WithCode(errors.PreconditionCode).
WithMessage("the tag %s configured as immutable, cannot be deleted", tag.Name) WithMessagef("the tag %s configured as immutable, cannot be deleted", tag.Name)
} }
return c.tagMgr.Delete(ctx, id) return c.tagMgr.Delete(ctx, id)
} }

View File

@ -178,17 +178,17 @@ func (c *controller) Count(ctx context.Context, query *q.Query) (int64, error) {
func (c *controller) Delete(ctx context.Context, id int) error { func (c *controller) Delete(ctx context.Context, id int) error {
// cleanup project member with the user // cleanup project member with the user
if err := c.memberMgr.DeleteMemberByUserID(ctx, id); err != nil { if err := c.memberMgr.DeleteMemberByUserID(ctx, id); err != nil {
return errors.UnknownError(err).WithMessage("delete user failed, user id: %v, cannot delete project user member, error:%v", id, err) return errors.UnknownError(err).WithMessagef("delete user failed, user id: %v, cannot delete project user member, error:%v", id, err)
} }
// delete oidc metadata under the user // delete oidc metadata under the user
if lib.GetAuthMode(ctx) == common.OIDCAuth { if lib.GetAuthMode(ctx) == common.OIDCAuth {
if err := c.oidcMetaMgr.DeleteByUserID(ctx, id); err != nil { if err := c.oidcMetaMgr.DeleteByUserID(ctx, id); err != nil {
return errors.UnknownError(err).WithMessage("delete user failed, user id: %v, cannot delete oidc user, error:%v", id, err) return errors.UnknownError(err).WithMessagef("delete user failed, user id: %v, cannot delete oidc user, error:%v", id, err)
} }
} }
gdprSetting, err := config.GDPRSetting(ctx) gdprSetting, err := config.GDPRSetting(ctx)
if err != nil { if err != nil {
return errors.UnknownError(err).WithMessage("failed to load GDPR setting: %v", err) return errors.UnknownError(err).WithMessagef("failed to load GDPR setting: %v", err)
} }
if gdprSetting.AuditLogs { if gdprSetting.AuditLogs {

View File

@ -81,7 +81,7 @@ func (c *controller) Update(ctx context.Context, id int, groupName string) error
return err return err
} }
if len(ug) == 0 { if len(ug) == 0 {
return errors.NotFoundError(nil).WithMessage("the user group with id %v is not found", id) return errors.NotFoundError(nil).WithMessagef("the user group with id %v is not found", id)
} }
return c.mgr.UpdateName(ctx, id, groupName) return c.mgr.UpdateName(ctx, id, groupName)
} }
@ -90,10 +90,10 @@ func (c *controller) Create(ctx context.Context, group model.UserGroup) (int, er
if group.GroupType == common.LDAPGroupType { if group.GroupType == common.LDAPGroupType {
ldapGroup, err := auth.SearchGroup(ctx, group.LdapGroupDN) ldapGroup, err := auth.SearchGroup(ctx, group.LdapGroupDN)
if err == ldap.ErrNotFound || ldapGroup == nil { if err == ldap.ErrNotFound || ldapGroup == nil {
return 0, errors.BadRequestError(nil).WithMessage("LDAP Group DN is not found: DN:%v", group.LdapGroupDN) return 0, errors.BadRequestError(nil).WithMessagef("LDAP Group DN is not found: DN:%v", group.LdapGroupDN)
} }
if err == ldap.ErrDNSyntax { if err == ldap.ErrDNSyntax {
return 0, errors.BadRequestError(nil).WithMessage("invalid DN syntax. DN: %v", group.LdapGroupDN) return 0, errors.BadRequestError(nil).WithMessagef("invalid DN syntax. DN: %v", group.LdapGroupDN)
} }
if err != nil { if err != nil {
return 0, err return 0, err
@ -102,7 +102,7 @@ func (c *controller) Create(ctx context.Context, group model.UserGroup) (int, er
id, err := c.mgr.Create(ctx, group) id, err := c.mgr.Create(ctx, group)
if err != nil && err == usergroup.ErrDupUserGroup { if err != nil && err == usergroup.ErrDupUserGroup {
return 0, errors.ConflictError(nil). return 0, errors.ConflictError(nil).
WithMessage("duplicate user group, group name:%v, group type: %v, ldap group DN: %v", WithMessagef("duplicate user group, group name:%v, group type: %v, ldap group DN: %v",
group.GroupName, group.GroupType, group.LdapGroupDN) group.GroupName, group.GroupType, group.LdapGroupDN)
} }

View File

@ -146,7 +146,7 @@ func (c *controller) GetTask(ctx context.Context, taskID int64) (*task.Task, err
if len(tasks) == 0 { if len(tasks) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("webhook task %d not found", taskID) WithMessagef("webhook task %d not found", taskID)
} }
return tasks[0], nil return tasks[0], nil
} }

View File

@ -102,7 +102,7 @@ func (d *DefaultAuthenticateHelper) OnBoardUser(_ context.Context, _ *models.Use
// SearchUser - Get user information from account repository // SearchUser - Get user information from account repository
func (d *DefaultAuthenticateHelper) SearchUser(_ context.Context, username string) (*models.User, error) { func (d *DefaultAuthenticateHelper) SearchUser(_ context.Context, username string) (*models.User, error) {
log.Errorf("Not support searching user, username: %s", username) log.Errorf("Not support searching user, username: %s", username)
return nil, libErrors.NotFoundError(ErrNotSupported).WithMessage("%s not found", username) return nil, libErrors.NotFoundError(ErrNotSupported).WithMessagef("%s not found", username)
} }
// PostAuthenticate - Update user information after authenticate, such as OnBoard or sync info etc // PostAuthenticate - Update user information after authenticate, such as OnBoard or sync info etc
@ -118,7 +118,7 @@ func (d *DefaultAuthenticateHelper) OnBoardGroup(_ context.Context, _ *model.Use
// SearchGroup - Search ldap group by group key, groupKey is the unique attribute of group in authenticator, for LDAP, the key is group DN // SearchGroup - Search ldap group by group key, groupKey is the unique attribute of group in authenticator, for LDAP, the key is group DN
func (d *DefaultAuthenticateHelper) SearchGroup(_ context.Context, groupKey string) (*model.UserGroup, error) { func (d *DefaultAuthenticateHelper) SearchGroup(_ context.Context, groupKey string) (*model.UserGroup, error) {
log.Errorf("Not support searching group, group key: %s", groupKey) log.Errorf("Not support searching group, group key: %s", groupKey)
return nil, libErrors.NotFoundError(ErrNotSupported).WithMessage("%s not found", groupKey) return nil, libErrors.NotFoundError(ErrNotSupported).WithMessagef("%s not found", groupKey)
} }
var registry = make(map[string]AuthenticateHelper) var registry = make(map[string]AuthenticateHelper)
@ -222,7 +222,7 @@ func SearchAndOnBoardUser(ctx context.Context, username string) (int, error) {
return 0, err return 0, err
} }
if user == nil { if user == nil {
return 0, libErrors.NotFoundError(nil).WithMessage(fmt.Sprintf("user %s is not found", username)) return 0, libErrors.NotFoundError(nil).WithMessagef("user %s is not found", username)
} }
err = OnBoardUser(ctx, user) err = OnBoardUser(ctx, user)
if err != nil { if err != nil {

View File

@ -262,7 +262,7 @@ func (l *Auth) SearchUser(ctx context.Context, username string) (*models.User, e
log.Debugf("Found ldap user %v", user) log.Debugf("Found ldap user %v", user)
} else { } else {
return nil, errors.NotFoundError(nil).WithMessage("no user found: %v", username) return nil, errors.NotFoundError(nil).WithMessagef("no user found: %v", username)
} }
return &user, nil return &user, nil
@ -292,7 +292,7 @@ func (l *Auth) SearchGroup(ctx context.Context, groupKey string) (*ugModel.UserG
} }
if len(userGroupList) == 0 { if len(userGroupList) == 0 {
return nil, errors.NotFoundError(nil).WithMessage("failed to searh ldap group with groupDN:%v", groupKey) return nil, errors.NotFoundError(nil).WithMessagef("failed to searh ldap group with groupDN:%v", groupKey)
} }
userGroup := ugModel.UserGroup{ userGroup := ugModel.UserGroup{
GroupName: userGroupList[0].Name, GroupName: userGroupList[0].Name,

View File

@ -39,7 +39,7 @@ func (h *Handler) Get() {
tokenCreator, ok := creatorMap[service] tokenCreator, ok := creatorMap[service]
if !ok { if !ok {
errMsg := fmt.Sprintf("Unable to handle service: %s", service) errMsg := fmt.Sprintf("Unable to handle service: %s", service)
log.Errorf(errMsg) log.Error(errMsg)
h.CustomAbort(http.StatusBadRequest, template.HTMLEscapeString(errMsg)) h.CustomAbort(http.StatusBadRequest, template.HTMLEscapeString(errMsg))
} }
token, err := tokenCreator.Create(request) token, err := tokenCreator.Create(request)

View File

@ -1,6 +1,6 @@
module github.com/goharbor/harbor/src module github.com/goharbor/harbor/src
go 1.22.3 go 1.23.2
require ( require (
github.com/FZambia/sentinel v1.1.0 github.com/FZambia/sentinel v1.1.0

View File

@ -713,7 +713,7 @@ func (gc *GarbageCollector) markDeleteFailed(ctx job.Context, blob *blobModels.B
return errors.Wrapf(err, "failed to mark gc candidate delete failed: %s, %s", blob.Digest, blob.Status) return errors.Wrapf(err, "failed to mark gc candidate delete failed: %s, %s", blob.Digest, blob.Status)
} }
if count == 0 { if count == 0 {
return errors.New(nil).WithMessage("no blob found to mark delete failed, ID:%d, digest:%s", blob.ID, blob.Digest).WithCode(errors.NotFoundCode) return errors.New(nil).WithMessagef("no blob found to mark delete failed, ID:%d, digest:%s", blob.ID, blob.Digest).WithCode(errors.NotFoundCode)
} }
return nil return nil
} }

View File

@ -201,24 +201,24 @@ func (sde *ScanDataExport) writeCsvFile(ctx job.Context, params job.Parameters,
return err return err
} }
projectIds := filterCriteria.Projects projectIDs := filterCriteria.Projects
if len(projectIds) == 0 { if len(projectIDs) == 0 {
return nil return nil
} }
// extract the repository ids if any repositories have been specified // extract the repository ids if any repositories have been specified
repoIds, err := sde.filterProcessor.ProcessRepositoryFilter(systemContext, filterCriteria.Repositories, projectIds) repoIDs, err := sde.filterProcessor.ProcessRepositoryFilter(systemContext, filterCriteria.Repositories, projectIDs)
if err != nil { if err != nil {
return err return err
} }
if len(repoIds) == 0 { if len(repoIDs) == 0 {
logger.Infof("No repositories found with specified names: %v", filterCriteria.Repositories) logger.Infof("No repositories found with specified names: %v", filterCriteria.Repositories)
return nil return nil
} }
// filter artifacts by tags // filter artifacts by tags
arts, err := sde.filterProcessor.ProcessTagFilter(systemContext, filterCriteria.Tags, repoIds) arts, err := sde.filterProcessor.ProcessTagFilter(systemContext, filterCriteria.Tags, repoIDs)
if err != nil { if err != nil {
return err return err
} }

View File

@ -14,7 +14,10 @@
package logger package logger
import "fmt" import (
"errors"
"fmt"
)
// Entry provides unique interfaces on top of multiple logger backends. // Entry provides unique interfaces on top of multiple logger backends.
// Entry also implements @Interface. // Entry also implements @Interface.
@ -115,7 +118,7 @@ func (e *Entry) Close() error {
} }
} }
if errMsg != "" { if errMsg != "" {
return fmt.Errorf(errMsg) return errors.New(errMsg)
} }
return nil return nil
} }

View File

@ -1,4 +1,4 @@
// Code generated by mockery v2.43.2. DO NOT EDIT. // Code generated by mockery v2.46.2. DO NOT EDIT.
package mgt package mgt

View File

@ -390,7 +390,7 @@ func toInt(v interface{}) int64 {
func hashKey(p *period.Policy) string { func hashKey(p *period.Policy) string {
key := p.JobName key := p.JobName
if p.JobParameters != nil && len(p.JobParameters) > 0 { if len(p.JobParameters) > 0 {
if bytes, err := json.Marshal(p.JobParameters); err == nil { if bytes, err := json.Marshal(p.JobParameters); err == nil {
key = fmt.Sprintf("%s:%s", key, string(bytes)) key = fmt.Sprintf("%s:%s", key, string(bytes))
} }

View File

@ -1,4 +1,4 @@
// Code generated by mockery v2.43.2. DO NOT EDIT. // Code generated by mockery v2.46.2. DO NOT EDIT.
package period package period

View File

@ -154,7 +154,7 @@ func (w *basicWorker) Start() error {
logger.Infof("Basic worker is started") logger.Infof("Basic worker is started")
// Start the reaper // Start the reaper
w.knownJobs.Range(func(k interface{}, v interface{}) bool { w.knownJobs.Range(func(k interface{}, _ interface{}) bool {
w.reaper.jobTypes = append(w.reaper.jobTypes, k.(string)) w.reaper.jobTypes = append(w.reaper.jobTypes, k.(string))
return true return true

View File

@ -136,7 +136,7 @@ func (r *reaper) syncOutdatedStats() error {
// Loop all the in progress jobs to check if they're really in progress or // Loop all the in progress jobs to check if they're really in progress or
// status is hung. // status is hung.
h := func(k string, v int64) (err error) { h := func(k string, _ int64) (err error) {
defer func() { defer func() {
if errs.IsObjectNotFoundError(err) { if errs.IsObjectNotFoundError(err) {
// As the job stats is lost and we don't have chance to restore it, then directly discard it. // As the job stats is lost and we don't have chance to restore it, then directly discard it.

View File

@ -1,4 +1,4 @@
// Code generated by mockery v2.43.2. DO NOT EDIT. // Code generated by mockery v2.46.2. DO NOT EDIT.
package cache package cache

View File

@ -35,10 +35,10 @@ func ValidateHTTPURL(s string) (string, error) {
} }
url, err := url.Parse(s) url, err := url.Parse(s)
if err != nil { if err != nil {
return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessage("invalid URL: %s", err.Error()) return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessagef("invalid URL: %s", err.Error())
} }
if url.Scheme != "http" && url.Scheme != "https" { if url.Scheme != "http" && url.Scheme != "https" {
return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessage("invalid HTTP scheme: %s", url.Scheme) return "", errors.New(nil).WithCode(errors.BadRequestCode).WithMessagef("invalid HTTP scheme: %s", url.Scheme)
} }
// To avoid SSRF security issue, refer to #3755 for more detail // To avoid SSRF security issue, refer to #3755 for more detail
return fmt.Sprintf("%s://%s%s", url.Scheme, url.Host, url.Path), nil return fmt.Sprintf("%s://%s%s", url.Scheme, url.Host, url.Path), nil

View File

@ -63,12 +63,18 @@ func (e *Error) MarshalJSON() ([]byte, error) {
}) })
} }
// WithMessage ... // WithMessagef ...
func (e *Error) WithMessage(format string, v ...interface{}) *Error { func (e *Error) WithMessagef(format string, v ...interface{}) *Error {
e.Message = fmt.Sprintf(format, v...) e.Message = fmt.Sprintf(format, v...)
return e return e
} }
// WithMessage ...
func (e *Error) WithMessage(message string) *Error {
e.Message = message
return e
}
// WithCode ... // WithCode ...
func (e *Error) WithCode(code string) *Error { func (e *Error) WithCode(code string) *Error {
e.Code = code e.Code = code

View File

@ -53,7 +53,7 @@ func AsNotFoundError(err error, messageFormat string, args ...interface{}) *erro
if errors.Is(err, orm.ErrNoRows) { if errors.Is(err, orm.ErrNoRows) {
e := errors.NotFoundError(nil) e := errors.NotFoundError(nil)
if len(messageFormat) > 0 { if len(messageFormat) > 0 {
_ = e.WithMessage(messageFormat, args...) _ = e.WithMessagef(messageFormat, args...)
} }
return e return e
} }
@ -66,7 +66,7 @@ func AsConflictError(err error, messageFormat string, args ...interface{}) *erro
if IsDuplicateKeyError(err) { if IsDuplicateKeyError(err) {
e := errors.New(err). e := errors.New(err).
WithCode(errors.ConflictCode). WithCode(errors.ConflictCode).
WithMessage(messageFormat, args...) WithMessagef(messageFormat, args...)
return e return e
} }
return nil return nil
@ -78,7 +78,7 @@ func AsForeignKeyError(err error, messageFormat string, args ...interface{}) *er
if isViolatingForeignKeyConstraintError(err) { if isViolatingForeignKeyConstraintError(err) {
e := errors.New(err). e := errors.New(err).
WithCode(errors.ViolateForeignKeyConstraintCode). WithCode(errors.ViolateForeignKeyConstraintCode).
WithMessage(messageFormat, args...) WithMessagef(messageFormat, args...)
return e return e
} }
return nil return nil

View File

@ -70,7 +70,7 @@ func parseKeywords(q string) (map[string]interface{}, error) {
if err != nil { if err != nil {
return nil, errors.New(err). return nil, errors.New(err).
WithCode(errors.BadRequestCode). WithCode(errors.BadRequestCode).
WithMessage("invalid query string value: %s", strs[1]) WithMessagef("invalid query string value: %s", strs[1])
} }
keywords[strs[0]] = value keywords[strs[0]] = value
} }

View File

@ -84,7 +84,7 @@ func GetRedisPool(name string, rawurl string, param *PoolParam) (*redis.Pool, er
Dial: func() (redis.Conn, error) { Dial: func() (redis.Conn, error) {
return redis.DialURL(rawurl) return redis.DialURL(rawurl)
}, },
TestOnBorrow: func(c redis.Conn, t time.Time) error { TestOnBorrow: func(c redis.Conn, _ time.Time) error {
_, err := c.Do("PING") _, err := c.Do("PING")
return err return err
}, },
@ -172,7 +172,7 @@ func getSentinelPool(u *url.URL, param *PoolParam, name string) (*redis.Pool, er
log.Debug(name, "dial redis master:", masterAddr, "db:", db) log.Debug(name, "dial redis master:", masterAddr, "db:", db)
return redis.Dial("tcp", masterAddr, redisOptions...) return redis.Dial("tcp", masterAddr, redisOptions...)
}, },
TestOnBorrow: func(c redis.Conn, t time.Time) error { TestOnBorrow: func(c redis.Conn, _ time.Time) error {
if !sentinel.TestRole(c, "master") { if !sentinel.TestRole(c, "master") {
return fmt.Errorf("check role failed, %s", name) return fmt.Errorf("check role failed, %s", name)
} }

View File

@ -94,7 +94,7 @@ func Get(kind, decoration, pattern, extras string) (selector.Selector, error) {
func Index() []*IndexedMeta { func Index() []*IndexedMeta {
all := make([]*IndexedMeta, 0) all := make([]*IndexedMeta, 0)
index.Range(func(k, v interface{}) bool { index.Range(func(_, v interface{}) bool {
if item, ok := v.(*indexedItem); ok { if item, ok := v.(*indexedItem); ok {
all = append(all, item.Meta) all = append(all, item.Meta)
return true return true

View File

@ -132,7 +132,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("accessory %d not found", id) return errors.NotFoundError(nil).WithMessagef("accessory %d not found", id)
} }
return nil return nil
} }

View File

@ -146,7 +146,7 @@ func (d *dao) GetByDigest(ctx context.Context, repository, digest string) (*Arti
} }
if len(artifacts) == 0 { if len(artifacts) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("artifact %s@%s not found", repository, digest) WithMessagef("artifact %s@%s not found", repository, digest)
} }
return artifacts[0], nil return artifacts[0], nil
} }
@ -181,7 +181,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("artifact %d not found", id) return errors.NotFoundError(nil).WithMessagef("artifact %d not found", id)
} }
return nil return nil
@ -197,7 +197,7 @@ func (d *dao) Update(ctx context.Context, artifact *Artifact, props ...string) e
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("artifact %d not found", artifact.ID) return errors.NotFoundError(nil).WithMessagef("artifact %d not found", artifact.ID)
} }
return nil return nil
} }
@ -261,7 +261,7 @@ func (d *dao) DeleteReference(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("artifact reference %d not found", id) return errors.NotFoundError(nil).WithMessagef("artifact reference %d not found", id)
} }
return nil return nil
} }

View File

@ -73,7 +73,7 @@ func (d *dao) Delete(ctx context.Context, id int64) (err error) {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("artifact trash %d not found", id) return errors.NotFoundError(nil).WithMessagef("artifact trash %d not found", id)
} }
return nil return nil
} }

View File

@ -207,7 +207,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("access %d not found", id) return errors.NotFoundError(nil).WithMessagef("access %d not found", id)
} }
return nil return nil
} }

View File

@ -385,7 +385,7 @@ func (d *dao) DeleteBlob(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("blob %d not found", id) return errors.NotFoundError(nil).WithMessagef("blob %d not found", id)
} }
return nil return nil
} }

View File

@ -140,7 +140,7 @@ func (m *manager) Update(ctx context.Context, blob *Blob) error {
func (m *manager) UpdateBlobStatus(ctx context.Context, blob *models.Blob) (int64, error) { func (m *manager) UpdateBlobStatus(ctx context.Context, blob *models.Blob) (int64, error) {
_, exist := models.StatusMap[blob.Status] _, exist := models.StatusMap[blob.Status]
if !exist { if !exist {
return -1, errors.New(nil).WithMessage("cannot update blob status, as the status is unknown. digest: %s, status: %s", blob.Digest, blob.Status) return -1, errors.New(nil).WithMessagef("cannot update blob status, as the status is unknown. digest: %s, status: %s", blob.Digest, blob.Status)
} }
return m.dao.UpdateBlobStatus(ctx, blob) return m.dao.UpdateBlobStatus(ctx, blob)
} }

View File

@ -87,7 +87,7 @@ func (e *Exporter) RegisterCollector(collectors ...collector) error {
func newServer(opt *Opt, _ *prometheus.Registry) *http.Server { func newServer(opt *Opt, _ *prometheus.Registry) *http.Server {
exporterMux := http.NewServeMux() exporterMux := http.NewServeMux()
exporterMux.Handle(opt.MetricsPath, promhttp.Handler()) exporterMux.Handle(opt.MetricsPath, promhttp.Handler())
exporterMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { exporterMux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`<html> _, _ = w.Write([]byte(`<html>
<head><title>Harbor Exporter</title></head> <head><title>Harbor Exporter</title></head>
<body> <body>

View File

@ -69,7 +69,7 @@ func (i *iDao) UpdateImmutableRule(ctx context.Context, projectID int64, ir *mod
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("immutable %d not found", ir.ID) return errors.NotFoundError(nil).WithMessagef("immutable %d not found", ir.ID)
} }
return nil return nil
} }
@ -86,7 +86,7 @@ func (i *iDao) ToggleImmutableRule(ctx context.Context, id int64, status bool) e
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("immutable %d not found", ir.ID) return errors.NotFoundError(nil).WithMessagef("immutable %d not found", ir.ID)
} }
return nil return nil
} }
@ -142,7 +142,7 @@ func (i *iDao) DeleteImmutableRule(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("immutable rule %d not found", id) return errors.NotFoundError(nil).WithMessagef("immutable rule %d not found", id)
} }
return nil return nil
} }

View File

@ -123,7 +123,7 @@ func (d *defaultDAO) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("label %d not found", id) return errors.NotFoundError(nil).WithMessagef("label %d not found", id)
} }
return nil return nil
} }
@ -184,7 +184,7 @@ func (d *defaultDAO) DeleteReference(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("label reference %d not found", id) return errors.NotFoundError(nil).WithMessagef("label reference %d not found", id)
} }
return nil return nil
} }

View File

@ -114,7 +114,7 @@ func (m *manager) RemoveFrom(ctx context.Context, labelID int64, artifactID int6
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("reference with label %d and artifact %d not found", labelID, artifactID) return errors.NotFoundError(nil).WithMessagef("reference with label %d and artifact %d not found", labelID, artifactID)
} }
return nil return nil
} }

View File

@ -52,9 +52,9 @@ func (l *Label) Valid() error {
} }
if l.Scope != common.LabelScopeGlobal && l.Scope != common.LabelScopeProject { if l.Scope != common.LabelScopeGlobal && l.Scope != common.LabelScopeProject {
return errors.New(nil).WithMessage("invalid: %s", l.Scope).WithCode(errors.BadRequestCode) return errors.New(nil).WithMessagef("invalid: %s", l.Scope).WithCode(errors.BadRequestCode)
} else if l.Scope == common.LabelScopeProject && l.ProjectID <= 0 { } else if l.Scope == common.LabelScopeProject && l.ProjectID <= 0 {
return errors.New(nil).WithMessage("invalid: %d", l.ProjectID).WithCode(errors.BadRequestCode) return errors.New(nil).WithMessagef("invalid: %d", l.ProjectID).WithCode(errors.BadRequestCode)
} }
return nil return nil
} }

View File

@ -67,7 +67,7 @@ func (m *manager) Get(ctx context.Context, projectID int64, memberID int) (*mode
} }
if len(pm) == 0 { if len(pm) == 0 {
return nil, errors.NotFoundError(nil). return nil, errors.NotFoundError(nil).
WithMessage("the project member is not found, project id %v, member id %v", projectID, memberID) WithMessagef("the project member is not found, project id %v, member id %v", projectID, memberID)
} }
return pm[0], nil return pm[0], nil
} }

View File

@ -150,7 +150,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("notificationPolicy %d not found", id) return errors.NotFoundError(nil).WithMessagef("notificationPolicy %d not found", id)
} }
return nil return nil
} }

View File

@ -80,7 +80,7 @@ func (md *metaDAO) Update(ctx context.Context, oidcUser *models.OIDCUser, props
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("oidc user data with id %d not found", oidcUser.ID) return errors.NotFoundError(nil).WithMessagef("oidc user data with id %d not found", oidcUser.ID)
} }
return nil return nil
} }

View File

@ -60,7 +60,7 @@ func (m *metaManager) GetBySubIss(ctx context.Context, sub, iss string) (*models
return nil, err return nil, err
} }
if len(l) == 0 { if len(l) == 0 {
return nil, errors.NotFoundError(nil).WithMessage("oidc info for user with issuer %s, subject %s not found", iss, sub) return nil, errors.NotFoundError(nil).WithMessagef("oidc info for user with issuer %s, subject %s not found", iss, sub)
} }
if len(l) > 1 { if len(l) > 1 {
logger.Warningf("Multiple oidc info records found for issuer %s, subject %s", iss, sub) logger.Warningf("Multiple oidc info records found for issuer %s, subject %s", iss, sub)
@ -79,7 +79,7 @@ func (m *metaManager) GetByUserID(ctx context.Context, uid int) (*models.OIDCUse
return nil, err return nil, err
} }
if len(l) == 0 { if len(l) == 0 {
return nil, errors.NotFoundError(nil).WithMessage("oidc info for user %d not found", uid) return nil, errors.NotFoundError(nil).WithMessagef("oidc info for user %d not found", uid)
} }
if len(l) > 1 { if len(l) > 1 {
logger.Warningf("%d records of oidc user Info found for user %d", len(l), uid) logger.Warningf("%d records of oidc user Info found for user %d", len(l), uid)

View File

@ -91,7 +91,7 @@ func (d *dao) Update(ctx context.Context, schema *policy.Schema, props ...string
} }
if id == 0 { if id == 0 {
return errors.NotFoundError(nil).WithMessage("policy %d not found", schema.ID) return errors.NotFoundError(nil).WithMessagef("policy %d not found", schema.ID)
} }
return nil return nil
@ -148,7 +148,7 @@ func (d *dao) Delete(ctx context.Context, id int64) (err error) {
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("policy %d not found", id) return errors.NotFoundError(nil).WithMessagef("policy %d not found", id)
} }
return nil return nil

View File

@ -132,13 +132,13 @@ func (s *Schema) ValidatePreheatPolicy() error {
if s.Trigger != nil && s.Trigger.Type == TriggerTypeScheduled && len(s.Trigger.Settings.Cron) > 0 { if s.Trigger != nil && s.Trigger.Type == TriggerTypeScheduled && len(s.Trigger.Settings.Cron) > 0 {
if err := utils.ValidateCronString(s.Trigger.Settings.Cron); err != nil { if err := utils.ValidateCronString(s.Trigger.Settings.Cron); err != nil {
return errors.New(nil).WithCode(errors.BadRequestCode). return errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid cron string for scheduled preheat: %s, error: %v", s.Trigger.Settings.Cron, err) WithMessagef("invalid cron string for scheduled preheat: %s, error: %v", s.Trigger.Settings.Cron, err)
} }
} }
// validate preheat scope // validate preheat scope
if s.Scope != "" && s.Scope != ScopeTypeSinglePeer && s.Scope != ScopeTypeAllPeers { if s.Scope != "" && s.Scope != ScopeTypeSinglePeer && s.Scope != ScopeTypeAllPeers {
return errors.New(nil).WithCode(errors.BadRequestCode).WithMessage("invalid scope for preheat policy: %s", s.Scope) return errors.New(nil).WithCode(errors.BadRequestCode).WithMessagef("invalid scope for preheat policy: %s", s.Scope)
} }
return nil return nil

View File

@ -40,7 +40,7 @@ func (s *regexpStore) Get(key string, build func(string) *regexp.Regexp) *regexp
func (s *regexpStore) Purge() { func (s *regexpStore) Purge() {
var keys []interface{} var keys []interface{}
s.entries.Range(func(key, value interface{}) bool { s.entries.Range(func(key, _ interface{}) bool {
keys = append(keys, key) keys = append(keys, key)
return true return true
}) })

View File

@ -71,12 +71,12 @@ type manager struct {
// Create creates project instance // Create creates project instance
func (m *manager) Create(ctx context.Context, project *models.Project) (int64, error) { func (m *manager) Create(ctx context.Context, project *models.Project) (int64, error) {
if project.OwnerID <= 0 { if project.OwnerID <= 0 {
return 0, errors.BadRequestError(nil).WithMessage("Owner is missing when creating project %s", project.Name) return 0, errors.BadRequestError(nil).WithMessagef("Owner is missing when creating project %s", project.Name)
} }
if utils.IsIllegalLength(project.Name, projectNameMinLen, projectNameMaxLen) { if utils.IsIllegalLength(project.Name, projectNameMinLen, projectNameMaxLen) {
format := "Project name %s is illegal in length. (greater than %d or less than %d)" format := "Project name %s is illegal in length. (greater than %d or less than %d)"
return 0, errors.BadRequestError(nil).WithMessage(format, project.Name, projectNameMaxLen, projectNameMinLen) return 0, errors.BadRequestError(nil).WithMessagef(format, project.Name, projectNameMaxLen, projectNameMinLen)
} }
legal := validProjectName.MatchString(project.Name) legal := validProjectName.MatchString(project.Name)
@ -107,7 +107,7 @@ func (m *manager) Get(ctx context.Context, idOrName interface{}) (*models.Projec
if ok { if ok {
// check white space in project name // check white space in project name
if strings.Contains(name, " ") { if strings.Contains(name, " ") {
return nil, errors.BadRequestError(nil).WithMessage("invalid project name: '%s'", name) return nil, errors.BadRequestError(nil).WithMessagef("invalid project name: '%s'", name)
} }
return m.dao.GetByName(ctx, name) return m.dao.GetByName(ctx, name)
} }

View File

@ -74,7 +74,7 @@ func (d *dao) DeletePermission(ctx context.Context, id int64) (err error) {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("role permission %d not found", id) return errors.NotFoundError(nil).WithMessagef("role permission %d not found", id)
} }
return nil return nil
} }
@ -106,7 +106,7 @@ func (d *dao) DeletePermissionsByRole(ctx context.Context, roleType string, role
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("role permission %s:%d not found", roleType, roleID) return errors.NotFoundError(nil).WithMessagef("role permission %s:%d not found", roleType, roleID)
} }
return err return err
} }
@ -132,7 +132,7 @@ func (d *dao) DeleteRbacPolicy(ctx context.Context, id int64) (err error) {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("rbac policy %d not found", id) return errors.NotFoundError(nil).WithMessagef("rbac policy %d not found", id)
} }
return nil return nil
} }

View File

@ -212,7 +212,7 @@ func (a adapter) DeleteManifest(repository, reference string) error {
if d == "" { if d == "" {
return errors.New(nil).WithCode(errors.NotFoundCode). return errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("%s:%s not found", repository, reference) WithMessagef("%s:%s not found", repository, reference)
} }
for _, t := range append(tags, d) { for _, t := range append(tags, d) {
req, err := http.NewRequest(http.MethodDelete, buildManifestURL(a.registry.URL, repository, t), nil) req, err := http.NewRequest(http.MethodDelete, buildManifestURL(a.registry.URL, repository, t), nil)

View File

@ -109,7 +109,7 @@ func (d *dao) Update(ctx context.Context, registry *Registry, props ...string) e
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("registry %d not found", registry.ID) return errors.NotFoundError(nil).WithMessagef("registry %d not found", registry.ID)
} }
return nil return nil
} }
@ -126,7 +126,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("registry %d not found", id) return errors.NotFoundError(nil).WithMessagef("registry %d not found", id)
} }
return nil return nil
} }

View File

@ -52,7 +52,7 @@ func (f *Filter) Validate() error {
rt := value rt := value
if !(rt == ResourceTypeArtifact || rt == ResourceTypeImage) { if !(rt == ResourceTypeArtifact || rt == ResourceTypeImage) {
return errors.New(nil).WithCode(errors.BadRequestCode). return errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid resource filter: %s", value) WithMessagef("invalid resource filter: %s", value)
} }
} }
if f.Type == FilterTypeName || f.Type == FilterTypeResource { if f.Type == FilterTypeName || f.Type == FilterTypeResource {
@ -81,7 +81,7 @@ func (f *Filter) Validate() error {
if f.Decoration != "" && f.Decoration != Matches && f.Decoration != Excludes { if f.Decoration != "" && f.Decoration != Matches && f.Decoration != Excludes {
return errors.New(nil).WithCode(errors.BadRequestCode). return errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid filter decoration, :%s", f.Decoration) WithMessagef("invalid filter decoration, :%s", f.Decoration)
} }
return nil return nil

View File

@ -49,7 +49,7 @@ func Ping(registry *model.Registry) (string, string, error) {
return challenge.Parameters["realm"], challenge.Parameters["service"], nil return challenge.Parameters["realm"], challenge.Parameters["service"], nil
} }
} }
return "", "", errors.New(nil).WithCode(errors.ChallengesUnsupportedCode).WithMessage("bearer auth scheme isn't supported: %v", challenges) return "", "", errors.New(nil).WithCode(errors.ChallengesUnsupportedCode).WithMessagef("bearer auth scheme isn't supported: %v", challenges)
} }
// ParseRepository parses the "repository" provided into two parts: namespace and the rest // ParseRepository parses the "repository" provided into two parts: namespace and the rest

View File

@ -125,7 +125,6 @@ func (a *authorizer) fetchToken(scopes []*scope) (*token, error) {
return nil, err return nil, err
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
message := fmt.Sprintf("http status code: %d, body: %s", resp.StatusCode, string(body))
code := errors.GeneralCode code := errors.GeneralCode
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusUnauthorized: case http.StatusUnauthorized:
@ -134,7 +133,7 @@ func (a *authorizer) fetchToken(scopes []*scope) (*token, error) {
code = errors.ForbiddenCode code = errors.ForbiddenCode
} }
return nil, errors.New(nil).WithCode(code). return nil, errors.New(nil).WithCode(code).
WithMessage(message) WithMessagef("http status code: %d, body: %s", resp.StatusCode, string(body))
} }
token := &token{} token := &token{}
if err = json.Unmarshal(body, token); err != nil { if err = json.Unmarshal(body, token); err != nil {

View File

@ -340,7 +340,7 @@ func (c *client) DeleteManifest(repository, reference string) error {
} }
if !exist { if !exist {
return errors.New(nil).WithCode(errors.NotFoundCode). return errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("%s:%s not found", repository, reference) WithMessagef("%s:%s not found", repository, reference)
} }
reference = string(desc.Digest) reference = string(desc.Digest)
} }
@ -669,7 +669,6 @@ func (c *client) do(req *http.Request) (*http.Response, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
message := fmt.Sprintf("http status code: %d, body: %s", resp.StatusCode, string(body))
code := errors.GeneralCode code := errors.GeneralCode
switch resp.StatusCode { switch resp.StatusCode {
case http.StatusUnauthorized: case http.StatusUnauthorized:
@ -682,7 +681,7 @@ func (c *client) do(req *http.Request) (*http.Response, error) {
code = errors.RateLimitCode code = errors.RateLimitCode
} }
return nil, errors.New(nil).WithCode(code). return nil, errors.New(nil).WithCode(code).
WithMessage(message) WithMessagef("http status code: %d, body: %s", resp.StatusCode, string(body))
} }
return resp, nil return resp, nil
} }

View File

@ -109,7 +109,7 @@ func (d *dao) Update(ctx context.Context, policy *model.Policy, props ...string)
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("replication policy %d not found", policy.ID) return errors.NotFoundError(nil).WithMessagef("replication policy %d not found", policy.ID)
} }
return nil return nil
} }
@ -126,7 +126,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("replication policy %d not found", id) return errors.NotFoundError(nil).WithMessagef("replication policy %d not found", id)
} }
return nil return nil
} }

View File

@ -113,7 +113,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("repository %d not found", id) return errors.NotFoundError(nil).WithMessagef("repository %d not found", id)
} }
return nil return nil
} }
@ -128,7 +128,7 @@ func (d *dao) Update(ctx context.Context, repository *model.RepoRecord, props ..
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("repository %d not found", repository.RepositoryID) return errors.NotFoundError(nil).WithMessagef("repository %d not found", repository.RepositoryID)
} }
return nil return nil
} }
@ -147,7 +147,7 @@ func (d *dao) AddPullCount(ctx context.Context, id int64, count uint64) error {
return err return err
} }
if num == 0 { if num == 0 {
return errors.New(nil).WithMessage("failed to increase repository pull count: %d", id) return errors.New(nil).WithMessagef("failed to increase repository pull count: %d", id)
} }
return nil return nil
} }

View File

@ -83,7 +83,7 @@ func (m *manager) GetByName(ctx context.Context, name string) (repository *model
} }
if len(repositories) == 0 { if len(repositories) == 0 {
return nil, errors.New(nil).WithCode(errors.NotFoundCode). return nil, errors.New(nil).WithCode(errors.NotFoundCode).
WithMessage("repository %s not found", name) WithMessagef("repository %s not found", name)
} }
return repositories[0], nil return repositories[0], nil
} }

View File

@ -69,7 +69,7 @@ func (m *Metadata) ValidateRetentionPolicy() error {
if ok && len(cronItem.(string)) > 0 { if ok && len(cronItem.(string)) > 0 {
if err := utils.ValidateCronString(cronItem.(string)); err != nil { if err := utils.ValidateCronString(cronItem.(string)); err != nil {
return errors.New(nil).WithCode(errors.BadRequestCode). return errors.New(nil).WithCode(errors.BadRequestCode).
WithMessage("invalid cron string for scheduled tag retention: %s, error: %v", cronItem.(string), err) WithMessagef("invalid cron string for scheduled tag retention: %s, error: %v", cronItem.(string), err)
} }
} }
} }

View File

@ -253,7 +253,7 @@ func Get(templateID string, parameters rule.Parameters) (rule.Evaluator, error)
func Index() []*Metadata { func Index() []*Metadata {
res := make([]*Metadata, 0) res := make([]*Metadata, 0)
index.Range(func(k, v interface{}) bool { index.Range(func(_, v interface{}) bool {
if item, ok := v.(*indexedItem); ok { if item, ok := v.(*indexedItem); ok {
res = append(res, item.Meta) res = append(res, item.Meta)
return true return true

View File

@ -78,7 +78,7 @@ func (d *dao) Update(ctx context.Context, r *model.Robot, props ...string) error
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("robot %d not found", r.ID) return errors.NotFoundError(nil).WithMessagef("robot %d not found", r.ID)
} }
return nil return nil
} }
@ -117,7 +117,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("robot account %d not found", id) return errors.NotFoundError(nil).WithMessagef("robot account %d not found", id)
} }
return nil return nil
} }

View File

@ -50,8 +50,8 @@ type VulnerabilityRecordDao interface {
DeleteForReport(ctx context.Context, reportUUID string) (int64, error) DeleteForReport(ctx context.Context, reportUUID string) (int64, error)
// DeleteForDigests deletes vulnerability records for a provided list of digests // DeleteForDigests deletes vulnerability records for a provided list of digests
DeleteForDigests(ctx context.Context, digests ...string) (int64, error) DeleteForDigests(ctx context.Context, digests ...string) (int64, error)
// GetRecordIdsForScanner gets record ids of vulnerability records for a scanner // GetRecordIDsForScanner gets record ids of vulnerability records for a scanner
GetRecordIdsForScanner(ctx context.Context, registrationUUID string) ([]int, error) GetRecordIDsForScanner(ctx context.Context, registrationUUID string) ([]int, error)
} }
// NewVulnerabilityRecordDao returns a new dao to handle vulnerability data // NewVulnerabilityRecordDao returns a new dao to handle vulnerability data
@ -230,17 +230,17 @@ func (v *vulnerabilityRecordDao) DeleteForDigests(ctx context.Context, digests .
return numRowsDeleted, nil return numRowsDeleted, nil
} }
// GetRecordIdsForScanner retrieves the internal Ids of the vulnerability records for a given scanner // GetRecordIDsForScanner retrieves the internal Ids of the vulnerability records for a given scanner
// identified by registrationUUID // identified by registrationUUID
func (v *vulnerabilityRecordDao) GetRecordIdsForScanner(ctx context.Context, registrationUUID string) ([]int, error) { func (v *vulnerabilityRecordDao) GetRecordIDsForScanner(ctx context.Context, registrationUUID string) ([]int, error) {
vulnRecordIds := make([]int, 0) vulnRecordIDs := make([]int, 0)
o, err := orm.FromContext(ctx) o, err := orm.FromContext(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
_, err = o.Raw("select id from vulnerability_record where registration_uuid = ?", registrationUUID).QueryRows(&vulnRecordIds) _, err = o.Raw("select id from vulnerability_record where registration_uuid = ?", registrationUUID).QueryRows(&vulnRecordIDs)
if err != nil { if err != nil {
return vulnRecordIds, err return vulnRecordIDs, err
} }
return vulnRecordIds, err return vulnRecordIDs, err
} }

View File

@ -180,7 +180,7 @@ func (suite *VulnerabilityTestSuite) TestGetVulnerabilityRecordsForScanner() {
// TestGetVulnerabilityRecordIdsForScanner gets vulnerability records for scanner // TestGetVulnerabilityRecordIdsForScanner gets vulnerability records for scanner
func (suite *VulnerabilityTestSuite) TestGetVulnerabilityRecordIdsForScanner() { func (suite *VulnerabilityTestSuite) TestGetVulnerabilityRecordIdsForScanner() {
vulns, err := suite.vulnerabilityRecordDao.GetRecordIdsForScanner(suite.Context(), "scannerId1") vulns, err := suite.vulnerabilityRecordDao.GetRecordIDsForScanner(suite.Context(), "scannerId1")
suite.NoError(err, "Error when fetching vulnerability records for report") suite.NoError(err, "Error when fetching vulnerability records for report")
suite.True(len(vulns) > 0) suite.True(len(vulns) > 0)
} }

View File

@ -154,7 +154,7 @@ func SetDefaultRegistration(ctx context.Context, UUID string) error {
return err return err
} }
if count == 0 { if count == 0 {
return errors.NotFoundError(nil).WithMessage("registration %s not found", UUID) return errors.NotFoundError(nil).WithMessagef("registration %s not found", UUID)
} }
qt2 := o.QueryTable(new(Registration)) qt2 := o.QueryTable(new(Registration))

View File

@ -30,8 +30,8 @@ import (
) )
type FilterProcessor interface { type FilterProcessor interface {
ProcessRepositoryFilter(ctx context.Context, filter string, projectIds []int64) ([]int64, error) ProcessRepositoryFilter(ctx context.Context, filter string, projectIDs []int64) ([]int64, error)
ProcessTagFilter(ctx context.Context, filter string, repositoryIds []int64) ([]*artifact.Artifact, error) ProcessTagFilter(ctx context.Context, filter string, repositoryIDs []int64) ([]*artifact.Artifact, error)
ProcessLabelFilter(ctx context.Context, labelIDs []int64, arts []*artifact.Artifact) ([]*artifact.Artifact, error) ProcessLabelFilter(ctx context.Context, labelIDs []int64, arts []*artifact.Artifact) ([]*artifact.Artifact, error)
} }
@ -52,12 +52,12 @@ func NewFilterProcessor() FilterProcessor {
} }
} }
func (dfp *DefaultFilterProcessor) ProcessRepositoryFilter(ctx context.Context, filter string, projectIds []int64) ([]int64, error) { func (dfp *DefaultFilterProcessor) ProcessRepositoryFilter(ctx context.Context, filter string, projectIDs []int64) ([]int64, error) {
sel := doublestar.New(doublestar.RepoMatches, filter, "") sel := doublestar.New(doublestar.RepoMatches, filter, "")
candidates := make([]*selector.Candidate, 0) candidates := make([]*selector.Candidate, 0)
allRepoIDs := make([]int64, 0) allRepoIDs := make([]int64, 0)
for _, projectID := range projectIds { for _, projectID := range projectIDs {
query := q.New(q.KeyWords{"ProjectID": projectID}) query := q.New(q.KeyWords{"ProjectID": projectID})
allRepos, err := dfp.repoMgr.List(ctx, query) allRepos, err := dfp.repoMgr.List(ctx, query)
if err != nil { if err != nil {
@ -87,7 +87,7 @@ func (dfp *DefaultFilterProcessor) ProcessRepositoryFilter(ctx context.Context,
return repoIDs, nil return repoIDs, nil
} }
func (dfp *DefaultFilterProcessor) ProcessTagFilter(ctx context.Context, filter string, repositoryIds []int64) ([]*artifact.Artifact, error) { func (dfp *DefaultFilterProcessor) ProcessTagFilter(ctx context.Context, filter string, repositoryIDs []int64) ([]*artifact.Artifact, error) {
arts := make([]*artifact.Artifact, 0) arts := make([]*artifact.Artifact, 0)
opts := &artifact.Option{ opts := &artifact.Option{
WithTag: true, WithTag: true,
@ -96,7 +96,7 @@ func (dfp *DefaultFilterProcessor) ProcessTagFilter(ctx context.Context, filter
// WithAccessory: true // WithAccessory: true
} }
// list all artifacts by repository id // list all artifacts by repository id
for _, repoID := range repositoryIds { for _, repoID := range repositoryIDs {
repoArts, err := dfp.artCtl.List(ctx, q.New(q.KeyWords{"RepositoryID": repoID}), opts) repoArts, err := dfp.artCtl.List(ctx, q.New(q.KeyWords{"RepositoryID": repoID}), opts)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -339,7 +339,7 @@ func (c *nativeToRelationalSchemaConverter) updateReport(ctx context.Context, vu
return err return err
} }
if len(reports) == 0 { if len(reports) == 0 {
return errors.New(nil).WithMessage("report not found, uuid:%v", reportUUID) return errors.New(nil).WithMessagef("report not found, uuid:%v", reportUUID)
} }
r := reports[0] r := reports[0]

View File

@ -73,7 +73,7 @@ func (h *scanHandler) MakePlaceHolder(ctx context.Context, art *artifact.Artifac
if len(oldReports) > 0 { if len(oldReports) > 0 {
for _, oldReport := range oldReports { for _, oldReport := range oldReports {
if !job.Status(oldReport.Status).Final() { if !job.Status(oldReport.Status).Final() {
return nil, errors.ConflictError(nil).WithMessage("a previous scan process is %s", oldReport.Status) return nil, errors.ConflictError(nil).WithMessagef("a previous scan process is %s", oldReport.Status)
} }
} }
@ -203,7 +203,7 @@ func (h *scanHandler) getScanTask(ctx context.Context, reportUUID string) (*task
} }
if len(tasks) == 0 { if len(tasks) == 0 {
return nil, errors.NotFoundError(nil).WithMessage("task for report %s not found", reportUUID) return nil, errors.NotFoundError(nil).WithMessagef("task for report %s not found", reportUUID)
} }
return tasks[0], nil return tasks[0], nil

View File

@ -114,7 +114,7 @@ func (d *dao) Delete(ctx context.Context, id int64) error {
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("schedule %d not found", id) return errors.NotFoundError(nil).WithMessagef("schedule %d not found", id)
} }
return nil return nil
@ -132,7 +132,7 @@ func (d *dao) Update(ctx context.Context, schedule *schedule, props ...string) e
return err return err
} }
if n == 0 { if n == 0 {
return errors.NotFoundError(nil).WithMessage("schedule %d not found", schedule.ID) return errors.NotFoundError(nil).WithMessagef("schedule %d not found", schedule.ID)
} }
return nil return nil
} }

Some files were not shown because too many files have changed in this diff Show More