fix: resolve the golint issues of source code (#18071)

Signed-off-by: chlins <chenyuzh@vmware.com>
This commit is contained in:
Chlins Zhang 2023-01-06 16:37:57 +08:00 committed by GitHub
parent b77d3aa153
commit 7ea89dc27f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 79 additions and 40 deletions

View File

@ -16,11 +16,12 @@ package http
import (
"crypto/tls"
"github.com/goharbor/harbor/src/lib/trace"
"net"
"net/http"
"time"
"github.com/goharbor/harbor/src/lib/trace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
@ -45,6 +46,7 @@ func init() {
}
}
// AddTracingWithGlobalTransport adds the global transport for tracing.
func AddTracingWithGlobalTransport() {
insecureHTTPTransport = otelhttp.NewTransport(insecureHTTPTransport, trace.HarborHTTPTraceOptions...)
secureHTTPTransport = otelhttp.NewTransport(secureHTTPTransport, trace.HarborHTTPTraceOptions...)
@ -86,14 +88,14 @@ func WithInsecureSkipVerify(skipVerify bool) func(*http.Transport) {
}
}
// WithMaxIdleConnsPerHost returns a TransportOption that configures the transport to use the specified number of idle connections per host
// WithMaxIdleConns returns a TransportOption that configures the transport to use the specified number of idle connections per host
func WithMaxIdleConns(maxIdleConns int) func(*http.Transport) {
return func(tr *http.Transport) {
tr.MaxIdleConns = maxIdleConns
}
}
// WithIdleConnTimeout returns a TransportOption that configures the transport to use the specified idle connection timeout
// WithIdleconnectionTimeout returns a TransportOption that configures the transport to use the specified idle connection timeout
func WithIdleconnectionTimeout(idleConnectionTimeout time.Duration) func(*http.Transport) {
return func(tr *http.Transport) {
tr.IdleConnTimeout = idleConnectionTimeout

View File

@ -41,6 +41,7 @@ type User struct {
OIDCUserMeta *OIDCUser `json:"oidc_user_meta,omitempty"`
}
// Users holds the slice of User.
type Users []*User
// MapByUserID returns map which key is UserID of the user and value is the user itself

View File

@ -19,10 +19,11 @@ import (
"context"
stderrors "errors"
"fmt"
accessorymodel "github.com/goharbor/harbor/src/pkg/accessory/model"
"strings"
"time"
accessorymodel "github.com/goharbor/harbor/src/pkg/accessory/model"
"github.com/goharbor/harbor/src/controller/artifact/processor/chart"
"github.com/goharbor/harbor/src/controller/artifact/processor/cnab"
"github.com/goharbor/harbor/src/controller/artifact/processor/image"
@ -141,6 +142,7 @@ type controller struct {
accessoryMgr accessory.Manager
}
// ArtOption is the model type of artifact option.
type ArtOption struct {
Tags []string
Accs []accessorymodel.AccessoryData

View File

@ -13,10 +13,12 @@ type reader struct {
limiter *rate.Limiter
}
// RateOpts is the model type of rate option.
type RateOpts struct {
Rate float64
}
// KBRATE is the pre-calculated const variable for KB.
const KBRATE = 1024 / 8
// NewReader returns a Reader that is rate limited

View File

@ -31,7 +31,7 @@ type Robot struct {
Permissions []*Permission `json:"permissions"`
}
// IsSysLevel, true is a system level robot, others are project level.
// IsSysLevel return true if is a system level robot, others are project level.
func (r *Robot) IsSysLevel() bool {
return r.Level == LEVELSYSTEM
}

View File

@ -148,6 +148,7 @@ func (t *Int64Type) get(str string) (interface{}, error) {
return parseInt64(str)
}
// Float64Type ...
type Float64Type struct{}
func (f *Float64Type) validate(str string) error {

View File

@ -9,6 +9,7 @@ import (
tracelib "github.com/goharbor/harbor/src/lib/trace"
)
// InitTraceConfig inits trace config.
func InitTraceConfig(ctx context.Context) {
cfgMgr, err := GetManager(common.InMemoryCfgManager)
if err != nil {

View File

@ -6,7 +6,7 @@ import (
var testcases = []struct {
url string
expectedUrl string
expectedURL string
valid bool
}{
{"http://harbor.foo.com", "http://harbor.foo.com", true},
@ -37,8 +37,8 @@ func TestValidateHTTPURL(t *testing.T) {
if err != nil {
t.Errorf("ValidateHTTPURL:%q gave err %v; want no error", test.url, err)
}
if url != test.expectedUrl {
t.Errorf("ValidateHTTPURL:%q gave %s; want %s", test.url, url, test.expectedUrl)
if url != test.expectedURL {
t.Errorf("ValidateHTTPURL:%q gave %s; want %s", test.url, url, test.expectedURL)
}
} else if !test.valid && err == nil {
t.Errorf("ValidateHTTPURL:%q gave <nil> error; want some error", test.url)

View File

@ -88,6 +88,7 @@ func IsConflictErr(err error) bool {
return IsErr(err, ConflictCode)
}
// IsChallengesUnsupportedErr checks whether the err chain contains ChallengesUnsupportedError
func IsChallengesUnsupportedErr(err error) bool {
return IsErr(err, ChallengesUnsupportedCode)
}

View File

@ -90,7 +90,7 @@ func Clone(ctx context.Context) context.Context {
type operationNameKey struct{}
// SetTransactionOpName sets the transaction operation name
// SetTransactionOpNameToContext sets the transaction operation name
func SetTransactionOpNameToContext(ctx context.Context, name string) context.Context {
if ctx == nil {
ctx = context.Background()
@ -255,8 +255,8 @@ func ParamPlaceholderForIn(n int) string {
// to DDL and other statements that do not accept parameters) to be used as part
// of an SQL statement. For example:
//
// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z")
// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date))
//
// Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be
// replaced by two backslashes (i.e. "\\") and the C-style escape identifier

View File

@ -16,7 +16,7 @@ package lib
import "strings"
// TrimsLineBreaks trims line breaks in string.
// TrimLineBreaks trims line breaks in string.
func TrimLineBreaks(s string) string {
escaped := strings.ReplaceAll(s, "\n", "")
escaped = strings.ReplaceAll(escaped, "\r", "")

View File

@ -19,12 +19,14 @@ import (
)
const (
// TraceEnvPrefix is the prefix of trace related env.
TraceEnvPrefix = "trace"
)
// C is the global configuration for trace
var C Config
// InitGlobalConfig inits global config.
func InitGlobalConfig(opts ...Option) {
C = NewConfig(opts...)
}
@ -72,97 +74,115 @@ func (c *Config) String() string {
return fmt.Sprintf("{Enabled: %v, ServiceName: %v, SampleRate: %v, Namespace: %v, ServiceName: %v, Jaeger: %v, Otel: %v}", c.Enabled, c.ServiceName, c.SampleRate, c.Namespace, c.ServiceName, c.Jaeger, c.Otel)
}
// Option is the wrapper for changing config.
type Option func(*Config)
// WithEnabled pass in the enabled.
func WithEnabled(enabled bool) Option {
return func(c *Config) {
c.Enabled = enabled
}
}
// WithSampleRate pass in the sample rate.
func WithSampleRate(sampleRate float64) Option {
return func(c *Config) {
c.SampleRate = sampleRate
}
}
// WithNamespace pass in the namespace.
func WithNamespace(namespace string) Option {
return func(c *Config) {
c.Namespace = namespace
}
}
// WithServiceName pass in the service name.
func WithServiceName(serviceName string) Option {
return func(c *Config) {
c.ServiceName = serviceName
}
}
// WithAttributes pass in the attributes.
func WithAttributes(attributes map[string]string) Option {
return func(c *Config) {
c.Attributes = attributes
}
}
// WithJaegerEndpoint pass in the jaeger endpoint.
func WithJaegerEndpoint(endpoint string) Option {
return func(c *Config) {
c.Jaeger.Endpoint = endpoint
}
}
// WithJaegerUsername pass in the jaeger username.
func WithJaegerUsername(username string) Option {
return func(c *Config) {
c.Jaeger.Username = username
}
}
// WithJaegerPassword pass in the jaeger password.
func WithJaegerPassword(password string) Option {
return func(c *Config) {
c.Jaeger.Password = password
}
}
// WithJaegerAgentHost pass in the jaeger agent host.
func WithJaegerAgentHost(host string) Option {
return func(c *Config) {
c.Jaeger.AgentHost = host
}
}
// WithJaegerAgentPort pass in the jaeger agent port.
func WithJaegerAgentPort(port string) Option {
return func(c *Config) {
c.Jaeger.AgentPort = port
}
}
// WithOtelEndpoint pass in the otel endpoint.
func WithOtelEndpoint(endpoint string) Option {
return func(c *Config) {
c.Otel.Endpoint = endpoint
}
}
// WithOtelURLPath pass in the url path.
func WithOtelURLPath(urlPath string) Option {
return func(c *Config) {
c.Otel.URLPath = urlPath
}
}
// WithOtelCompression pass in the otel compression.
func WithOtelCompression(compression bool) Option {
return func(c *Config) {
c.Otel.Compression = compression
}
}
// WithOtelInsecure pass in the otel insecure.
func WithOtelInsecure(insecure bool) Option {
return func(c *Config) {
c.Otel.Insecure = insecure
}
}
// WithOtelTimeout pass in the otel timeout.
func WithOtelTimeout(timeout int) Option {
return func(c *Config) {
c.Otel.Timeout = timeout
}
}
// NewConfig returns config which generated by passed in options.
func NewConfig(opts ...Option) Config {
c := Config{Otel: OtelConfig{}, Jaeger: JaegerConfig{}}
for _, opt := range opts {
@ -171,7 +191,7 @@ func NewConfig(opts ...Option) Config {
return c
}
// GetConfig returns the global configuration for trace
// GetGlobalConfig returns the global configuration for trace
func GetGlobalConfig() Config {
return C
}

View File

@ -113,7 +113,7 @@ func (s ShutdownFunc) Shutdown() {
s()
}
// Init initializes the trace provider
// InitGlobalTracer initializes the trace provider
func InitGlobalTracer(ctx context.Context) ShutdownFunc {
if !Enabled() {
otel.SetTracerProvider(oteltrace.NewNoopTracerProvider())

View File

@ -16,12 +16,12 @@ package accessory
import (
"context"
"github.com/goharbor/harbor/src/lib/errors"
"github.com/goharbor/harbor/src/lib/icon"
"github.com/goharbor/harbor/src/lib/q"
"github.com/goharbor/harbor/src/pkg/accessory/dao"
"github.com/goharbor/harbor/src/pkg/accessory/model"
_ "github.com/goharbor/harbor/src/pkg/accessory/model/base"
_ "github.com/goharbor/harbor/src/pkg/accessory/model/cosign"
)

View File

@ -17,9 +17,10 @@ package model
import (
"encoding/json"
"fmt"
"github.com/goharbor/harbor/src/lib/errors"
"sync"
"time"
"github.com/goharbor/harbor/src/lib/errors"
)
const (
@ -31,11 +32,13 @@ const (
RefHard = "hard"
)
// RefProvider is the interface for ref provider.
type RefProvider interface {
// Kind returns reference Kind.
Kind() string
}
// RefIdentifier is the interface for ref identifier.
/*
RefIdentifier
@ -43,10 +46,12 @@ Soft reference: The accessory is not tied to the subject manifest.
Hard reference: The accessory is tied to the subject manifest.
Deletion
1. Soft Reference: If the linkage is Soft Reference, when the subject artifact is removed, the linkage will be removed as well, the accessory artifact becomes an individual artifact.
2. Hard Reference: If the linkage is Hard Reference, the accessory artifact will be removed together with the subject artifact.
Garbage Collection
1. Soft Reference: If the linkage is Soft Reference, Harbor treats the accessory as normal artifact and will not set it as the GC candidate.
2. Hard Reference: If the linkage is Hard Reference, Harbor treats the accessory as an extra stuff of the subject artifact. It means, it being tied to the subject artifact and will be GCed whenever the subject artifact is marked and deleted.
*/

View File

@ -103,7 +103,7 @@ func (p *Project) ContentTrustEnabled() bool {
return isTrue(enabled)
}
// VulPrevented ...
// ContentTrustCosignEnabled ...
func (p *Project) ContentTrustCosignEnabled() bool {
enabled, exist := p.GetMetadata(ProMetaEnableContentTrustCosign)
if !exist {

View File

@ -114,11 +114,11 @@ func (c *Client) ListProjects(name string) ([]*Project, error) {
}
// ListProjectsWithQuery lists projects with query
func (c *Client) ListProjectsWithQuery(q string, with_detail bool) ([]*Project, error) {
func (c *Client) ListProjectsWithQuery(q string, withDetail bool) ([]*Project, error) {
projects := []*Project{}
// if old version does not support query, it will fallback to normal
// list(list all).
url := fmt.Sprintf("%s/projects?q=%s&with_detail=%t", c.BasePath(), url.QueryEscape(q), with_detail)
url := fmt.Sprintf("%s/projects?q=%s&with_detail=%t", c.BasePath(), url.QueryEscape(q), withDetail)
if err := c.C.GetAndIteratePagination(url, &projects); err != nil {
return nil, err
}

View File

@ -40,6 +40,7 @@ type Filter struct {
Decoration string `json:"decoration,omitempty"`
}
// Validate checks the correctness of filter.
func (f *Filter) Validate() error {
switch f.Type {
case FilterTypeResource, FilterTypeName, FilterTypeTag:

View File

@ -33,6 +33,7 @@ func GetHTTPTransport(insecure bool) http.RoundTripper {
return commonhttp.GetHTTPTransport()
}
// Ping sends the ping request to registry.
func Ping(registry *model.Registry) (string, string, error) {
client := &http.Client{
Transport: GetHTTPTransport(registry.Insecure),

View File

@ -347,7 +347,7 @@ func (e *executionDAO) querySetter(ctx context.Context, query *q.Query) (orm.Que
args = append(args, item)
}
args = append(args, value)
inClause, err := orm.CreateInClause(ctx, buildInClauseSqlForExtraAttrs(keys), args...)
inClause, err := orm.CreateInClause(ctx, buildInClauseSQLForExtraAttrs(keys), args...)
if err != nil {
return nil, err
}
@ -358,7 +358,7 @@ func (e *executionDAO) querySetter(ctx context.Context, query *q.Query) (orm.Que
}
// Param keys is strings.Split() after trim "extra_attrs."/"ExtraAttrs." prefix
func buildInClauseSqlForExtraAttrs(keys []string) string {
func buildInClauseSQLForExtraAttrs(keys []string) string {
switch len(keys) {
case 0:
// won't fall into this case, as the if condition on "keyPrefix == key"

View File

@ -346,7 +346,7 @@ func Test_buildInClauseSqlForExtraAttrs(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := buildInClauseSqlForExtraAttrs(tt.args.keys); got != tt.want {
if got := buildInClauseSQLForExtraAttrs(tt.args.keys); got != tt.want {
t.Errorf("buildInClauseSqlForExtraAttrs() = %v, want %v", got, tt.want)
}
})

View File

@ -3,6 +3,10 @@ package cosign
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"github.com/docker/distribution/reference"
"github.com/goharbor/harbor/src/controller/artifact"
"github.com/goharbor/harbor/src/lib"
@ -14,9 +18,6 @@ import (
"github.com/goharbor/harbor/src/pkg/distribution"
"github.com/goharbor/harbor/src/server/middleware"
digest "github.com/opencontainers/go-digest"
"io/ioutil"
"net/http"
"regexp"
)
var (
@ -29,7 +30,7 @@ var (
mediaTypeCosignLayer = "application/vnd.dev.cosign.simplesigning.v1+json"
)
// CosignSignatureMiddleware middleware to record the linkeage of artifact and its accessory
// Middleware to record the linkeage of artifact and its accessory
/* PUT /v2/library/hello-world/manifests/sha256-1b26826f602946860c279fce658f31050cff2c596583af237d971f4629b57792.sig
{
"schemaVersion":2,
@ -50,7 +51,7 @@ var (
]
}
*/
func CosignSignatureMiddleware() func(http.Handler) http.Handler {
func Middleware() func(http.Handler) http.Handler {
return middleware.AfterResponse(func(w http.ResponseWriter, r *http.Request, statusCode int) error {
if statusCode != http.StatusCreated {
return nil

View File

@ -2,6 +2,12 @@ package cosign
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/goharbor/harbor/src/controller/repository"
"github.com/goharbor/harbor/src/lib"
"github.com/goharbor/harbor/src/lib/q"
@ -12,11 +18,6 @@ import (
"github.com/goharbor/harbor/src/pkg/distribution"
htesting "github.com/goharbor/harbor/src/testing"
"github.com/stretchr/testify/suite"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type MiddlewareTestSuite struct {
@ -127,15 +128,15 @@ func (suite *MiddlewareTestSuite) TestCosignSignature() {
ref := fmt.Sprintf("%s.sig", strings.ReplaceAll(subArtDigest, "sha256:", "sha256-"))
_, descriptor, req := suite.prepare(name, ref)
_, repoId, err := repository.Ctl.Ensure(suite.Context(), name)
_, repoID, err := repository.Ctl.Ensure(suite.Context(), name)
suite.Nil(err)
subjectArtID := suite.addArt(projectID, repoId, name, subArtDigest)
artID := suite.addArt(projectID, repoId, name, descriptor.Digest.String())
subjectArtID := suite.addArt(projectID, repoID, name, subArtDigest)
artID := suite.addArt(projectID, repoID, name, descriptor.Digest.String())
suite.Nil(err)
res := httptest.NewRecorder()
next := suite.NextHandler(http.StatusCreated, map[string]string{"Docker-Content-Digest": descriptor.Digest.String()})
CosignSignatureMiddleware()(next).ServeHTTP(res, req)
Middleware()(next).ServeHTTP(res, req)
suite.Equal(http.StatusCreated, res.Code)
accs, err := accessory.Mgr.List(suite.Context(), &q.Query{
@ -158,13 +159,13 @@ func (suite *MiddlewareTestSuite) TestCosignSignatureDup() {
ref := fmt.Sprintf("%s.sig", strings.ReplaceAll(subArtDigest, "sha256:", "sha256-"))
_, descriptor, req := suite.prepare(name, ref)
_, repoId, err := repository.Ctl.Ensure(suite.Context(), name)
_, repoID, err := repository.Ctl.Ensure(suite.Context(), name)
suite.Nil(err)
accID := suite.addArtAcc(projectID, repoId, name, subArtDigest, descriptor.Digest.String())
accID := suite.addArtAcc(projectID, repoID, name, subArtDigest, descriptor.Digest.String())
res := httptest.NewRecorder()
next := suite.NextHandler(http.StatusCreated, map[string]string{"Docker-Content-Digest": descriptor.Digest.String()})
CosignSignatureMiddleware()(next).ServeHTTP(res, req)
Middleware()(next).ServeHTTP(res, req)
suite.Equal(http.StatusCreated, res.Code)
accs, err := accessory.Mgr.List(suite.Context(), &q.Query{

View File

@ -79,7 +79,7 @@ func RegisterRoutes() {
Middleware(repoproxy.DisableBlobAndManifestUploadMiddleware()).
Middleware(immutable.Middleware()).
Middleware(quota.PutManifestMiddleware()).
Middleware(cosign.CosignSignatureMiddleware()).
Middleware(cosign.Middleware()).
Middleware(blob.PutManifestMiddleware()).
HandlerFunc(putManifest)
// blob head