Skip to content

Commit

Permalink
Merge pull request #3187 from cupakob/fix-imported-package-name-as-na…
Browse files Browse the repository at this point in the history
…me-identifier

🐛 Fix probable bug: imported package name as name identifier
  • Loading branch information
kcp-ci-bot authored Oct 26, 2024
2 parents 9d7828f + 728f32e commit 5342cf0
Show file tree
Hide file tree
Showing 23 changed files with 91 additions and 91 deletions.
4 changes: 2 additions & 2 deletions cli/cmd/kubectl-kcp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ func main() {
flags := pflag.NewFlagSet("kubectl-kcp", pflag.ExitOnError)
pflag.CommandLine = flags

cmd := cmd.KubectlKcpCommand()
if err := cmd.Execute(); err != nil {
command := cmd.KubectlKcpCommand()
if err := command.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/sharded-test-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import (
"k8s.io/client-go/util/retry"

"github.com/kcp-dev/kcp/cmd/sharded-test-server/third_party/library-go/crypto"
shard "github.com/kcp-dev/kcp/cmd/test-server/kcp"
testshard "github.com/kcp-dev/kcp/cmd/test-server/kcp"
"github.com/kcp-dev/kcp/pkg/authorization/bootstrap"
"github.com/kcp-dev/kcp/sdk/apis/core"
kcpclientset "github.com/kcp-dev/kcp/sdk/client/clientset/versioned/cluster"
Expand Down Expand Up @@ -221,7 +221,7 @@ func start(proxyFlags, shardFlags []string, logDirPath, workDirPath string, numb
}

// start shards
var shards []*shard.Shard
var shards []*testshard.Shard
for i := 0; i < numberOfShards; i++ {
shard, err := newShard(ctx, i, shardFlags, standaloneVW, servingCA, hostIP.String(), logDirPath, workDirPath, cacheServerConfigPath, clientCA)
if err != nil {
Expand Down Expand Up @@ -259,7 +259,7 @@ func start(proxyFlags, shardFlags []string, logDirPath, workDirPath string, numb
if err != nil {
return err
}
err = shard.ScrapeMetrics(ctx, s, workDirPath)
err = testshard.ScrapeMetrics(ctx, s, workDirPath)
if err != nil {
return err
}
Expand Down
22 changes: 11 additions & 11 deletions cmd/sharded-test-server/third_party/library-go/crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -723,10 +723,10 @@ func GetServerCert(certFile, keyFile string, hostnames sets.Set[string]) (*TLSCe
return nil, err
}

cert := server.Certs[0]
certificate := server.Certs[0]
ips, dns := IPAddressesDNSNames(sets.List[string](hostnames))
missingIps := ipsNotInSlice(ips, cert.IPAddresses)
missingDns := stringsNotInSlice(dns, cert.DNSNames)
missingIps := ipsNotInSlice(ips, certificate.IPAddresses)
missingDns := stringsNotInSlice(dns, certificate.DNSNames)
if len(missingIps) == 0 && len(missingDns) == 0 {
klog.Background().V(4).WithValues("certFile", certFile).Info("found existing server certificate")
return server, nil
Expand Down Expand Up @@ -1034,12 +1034,12 @@ func CertsFromPEM(pemCerts []byte) ([]*x509.Certificate, error) {
continue
}

cert, err := x509.ParseCertificate(block.Bytes)
certiicate, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return certs, err
}

certs = append(certs, cert)
certs = append(certs, certiicate)
ok = true
}

Expand Down Expand Up @@ -1105,8 +1105,8 @@ func signCertificate(template *x509.Certificate, requestKey crypto.PublicKey, is

func EncodeCertificates(certs ...*x509.Certificate) ([]byte, error) {
b := bytes.Buffer{}
for _, cert := range certs {
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil {
for _, certificate := range certs {
if err := pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: certificate.Raw}); err != nil {
return []byte{}, err
}
}
Expand Down Expand Up @@ -1135,22 +1135,22 @@ func encodeKey(key crypto.PrivateKey) ([]byte, error) {
}

func writeCertificates(f io.Writer, certs ...*x509.Certificate) error {
bytes, err := EncodeCertificates(certs...)
encoded, err := EncodeCertificates(certs...)
if err != nil {
return err
}
if _, err := f.Write(bytes); err != nil {
if _, err := f.Write(encoded); err != nil {
return err
}

return nil
}
func writeKeyFile(f io.Writer, key crypto.PrivateKey) error {
bytes, err := encodeKey(key)
b, err := encodeKey(key)
if err != nil {
return err
}
if _, err := f.Write(bytes); err != nil {
if _, err := f.Write(b); err != nil {
return err
}

Expand Down
12 changes: 6 additions & 6 deletions pkg/crdpuller/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,12 +223,12 @@ func (sp *schemaPuller) PullCRDs(ctx context.Context, resourceNames ...string) (
}
swaggerSpecDefinitionName := protoSchema.GetPath().String()

var errors []error
var errs []error
converter := &SchemaConverter{
schemaProps: &schemaProps,
schemaName: swaggerSpecDefinitionName,
visited: sets.New[string](),
errors: &errors,
errors: &errs,
}
protoSchema.Accept(converter)
if len(*converter.errors) > 0 {
Expand Down Expand Up @@ -334,12 +334,12 @@ type SchemaConverter struct {
func Convert(protoSchema proto.Schema, schemaProps *apiextensionsv1.JSONSchemaProps) []error {
swaggerSpecDefinitionName := protoSchema.GetPath().String()

var errors []error
var errs []error
converter := &SchemaConverter{
schemaProps: schemaProps,
schemaName: swaggerSpecDefinitionName,
visited: sets.New[string](),
errors: &errors,
errors: &errs,
}
protoSchema.Accept(converter)
return *converter.errors
Expand Down Expand Up @@ -631,9 +631,9 @@ var knownSchemas map[string]apiextensionsv1.JSONSchemaProps
func init() {
knownSchemas = map[string]apiextensionsv1.JSONSchemaProps{}
for pkgName, schemas := range knownPackages {
for typeName, schema := range schemas {
for typeName, s := range schemas {
schemaName := util.ToRESTFriendlyName(pkgName + "." + typeName)
knownSchemas[schemaName] = schema
knownSchemas[schemaName] = s
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/index/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,11 @@ func (c *State) Lookup(path logicalcluster.Path) (Result, bool) {
if foundMount {
mount, err := tenancyv1alpha1.ParseTenancyMountAnnotation(val)
if !(err != nil || mount == nil || mount.MountStatus.URL == "") {
url, err := url.Parse(mount.MountStatus.URL)
u, err := url.Parse(mount.MountStatus.URL)
if err != nil {
// default to workspace itself.
} else {
return Result{URL: url.String()}, true
return Result{URL: u.String()}, true
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/informer/informer.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,18 +313,18 @@ func (d *GenericDiscoveringDynamicSharedInformerFactory[Informer, Lister, Generi

klog.Background().V(2).WithValues("gvr", gvr).Info("adding dynamic informer for gvr")

indexers := cache.Indexers{}
cacheIndexers := cache.Indexers{}
for k, v := range d.indexers {
if k == cache.NamespaceIndex {
// Don't allow overriding NamespaceIndex
continue
}

indexers[k] = v
cacheIndexers[k] = v
}

// Definitely need to create it
inf = d.newInformer(gvr, resyncPeriod, indexers)
inf = d.newInformer(gvr, resyncPeriod, cacheIndexers)

_, _ = inf.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: d.filterFunc,
Expand Down
4 changes: 2 additions & 2 deletions pkg/reconciler/apis/apibinding/apibinding_reconcile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -459,12 +459,12 @@ func TestReconcileBinding(t *testing.T) {

require.Equal(t, "org-some-workspace", clusterName.String())

schema, ok := apiResourceSchemas[name]
s, ok := apiResourceSchemas[name]
if !ok {
return nil, apierrors.NewNotFound(apisv1alpha1.Resource("apiresourceschemas"), name)
}

return schema, nil
return s, nil
},
getCRD: func(clusterName logicalcluster.Name, name string) (*apiextensionsv1.CustomResourceDefinition, error) {
require.Equal(t, SystemBoundCRDsClusterName, clusterName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,11 @@ func ensureRemaining(cacheObject *unstructured.Unstructured, localObject *unstru
}

func toUnstructured(obj interface{}) (*unstructured.Unstructured, error) {
unstructured := &unstructured.Unstructured{Object: map[string]interface{}{}}
u := &unstructured.Unstructured{Object: map[string]interface{}{}}
raw, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
if err != nil {
return nil, err
}
unstructured.Object = raw
return unstructured, nil
u.Object = raw
return u, nil
}
10 changes: 5 additions & 5 deletions pkg/reconciler/topology/partitionset/partitionset_reconcile.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,17 +194,17 @@ func (c *controller) reconcile(ctx context.Context, partitionSet *topologyv1alph
// so that Partitions not referring to any Shard would not get created.
func partition(shards []*corev1alpha1.Shard, dimensions []string, shardSelectorLabels map[string]string) (matchLabelsMap map[string]map[string]string) {
matchLabelsMap = make(map[string]map[string]string)
labels := make([]string, len(dimensions), len(dimensions)+len(shardSelectorLabels))
copy(labels, dimensions)
l := make([]string, len(dimensions), len(dimensions)+len(shardSelectorLabels))
copy(l, dimensions)
for label := range shardSelectorLabels {
labels = append(labels, label)
l = append(l, label)
}
sort.Strings(labels) // Sorting for consistent comparison.
sort.Strings(l) // Sorting for consistent comparison.
for _, shard := range shards {
key := ""
selector := make(map[string]string)
matchingLabels := true
for _, label := range labels {
for _, label := range l {
labelValue, ok := shard.Labels[label]
if !ok {
matchingLabels = false
Expand Down
6 changes: 3 additions & 3 deletions pkg/server/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,13 @@ func TestProcessResourceIdentity(t *testing.T) {

for name, test := range tests {
t.Run(name, func(t *testing.T) {
url, err := url.Parse(test.path)
u, err := url.Parse(test.path)
require.NoError(t, err, "error parsing path %q to URL", test.path)

checkRawPath := url.RawPath != ""
checkRawPath := u.RawPath != ""

req := &http.Request{
URL: url,
URL: u,
Method: http.MethodGet,
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/server/localproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,14 @@ func WithLocalProxy(
}

if r.URL != "" {
url, err := url.Parse(r.URL)
u, err := url.Parse(r.URL)
if err != nil {
logger.WithValues("cluster", cluster.Name, "url", r.URL).Error(err, "invalid url")
http.Error(w, "invalid url", http.StatusInternalServerError)
return
}
logger.WithValues("from", path, "to", r.URL).V(4).Info("mounting cluster")
proxy := httputil.NewSingleHostReverseProxy(url)
proxy := httputil.NewSingleHostReverseProxy(u)
// TODO(mjudeikis): remove this once we have a real cert wired in dev mode
proxy.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
Expand Down
8 changes: 4 additions & 4 deletions pkg/server/openapiv3/servicecache.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,9 @@ func (c *ServiceCache) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.V(7).Info("Creating new OpenAPI v3 service")

// create a new OpenAPI service
mux := mux.NewPathRecorderMux("cluster-aware-openapi-v3")
m := mux.NewPathRecorderMux("cluster-aware-openapi-v3")
service := handler3.NewOpenAPIService()
err := service.RegisterOpenAPIV3VersionedService("/openapi/v3", mux)
err := service.RegisterOpenAPIV3VersionedService("/openapi/v3", m)
if err != nil {
responsewriters.InternalError(w, r, err)
return
Expand All @@ -181,8 +181,8 @@ func (c *ServiceCache) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// remember for next time
c.services.Add(key, mux)
entry = mux
c.services.Add(key, m)
entry = m
} else {
log.V(7).Info("Reusing OpenAPI v3 service from cache")
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/virtual/apiexport/schemas/builtin/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ func IsBuiltInAPI(gr apisv1alpha1.GroupResource) bool {

// GetBuiltInAPISchema retrieves the APIResourceSchema for a built-in API.
func GetBuiltInAPISchema(gr apisv1alpha1.GroupResource) (*apisv1alpha1.APIResourceSchema, error) {
schema, exists := builtInAPIResourceSchemas[gr]
s, exists := builtInAPIResourceSchemas[gr]
if !exists {
return nil, fmt.Errorf("no schema found for built-in API %s.%s", gr.Resource, gr.Group)
}
return schema, nil
return s, nil
}

// builtInAPIResourceSchemas contains a list of APIResourceSchema for built-in
Expand Down
6 changes: 3 additions & 3 deletions pkg/virtual/framework/dynamic/apiserver/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -901,10 +901,10 @@ func TestBuildOpenAPIModelsForApply(t *testing.T) {
},
}

schema := exampleAPIResourceSchema()
s := exampleAPIResourceSchema()
for i, test := range tests {
_ = schema.Spec.Versions[0].SetSchema(test.OpenAPIV3Schema)
swagger, err := buildOpenAPIV2(schema, &schema.Spec.Versions[0], builder.Options{V2: true, StripValueValidation: true, StripNullable: true, AllowNonStructural: false})
_ = s.Spec.Versions[0].SetSchema(test.OpenAPIV3Schema)
swagger, err := buildOpenAPIV2(s, &s.Spec.Versions[0], builder.Options{V2: true, StripValueValidation: true, StripNullable: true, AllowNonStructural: false})
require.NoError(t, err)

openAPIModels, err := utilopenapi.ToProtoModels(swagger)
Expand Down
10 changes: 5 additions & 5 deletions pkg/virtual/framework/fixedgvs/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ func (vw *FixedGroupVersionsVirtualWorkspace) Register(vwName string, rootAPISer
StorageBuilders: make(map[string]func(apiGroupAPIServerConfig genericapiserver.CompletedConfig) (restStorage.Storage, error)),
},
}
for resourceName, builder := range restStorageBuilders {
cfg.ExtraConfig.StorageBuilders[resourceName] = builder
for resourceName, restStorageBuilder := range restStorageBuilders {
cfg.ExtraConfig.StorageBuilders[resourceName] = restStorageBuilder
}

scheme := runtime.NewScheme()
Expand Down Expand Up @@ -87,12 +87,12 @@ func (vw *FixedGroupVersionsVirtualWorkspace) Register(vwName string, rootAPISer
}

if groupVersionAPISet.OpenAPIDefinitions != nil {
spec, err := builder.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(server.GenericAPIServer.Handler.GoRestfulContainer.RegisteredWebServices()), config.GenericConfig.OpenAPIConfig)
openAPISpec, err := builder.BuildOpenAPISpecFromRoutes(restfuladapter.AdaptWebServices(server.GenericAPIServer.Handler.GoRestfulContainer.RegisteredWebServices()), config.GenericConfig.OpenAPIConfig)
if err != nil {
return nil, err
}
spec.Definitions = handler.PruneDefaults(spec.Definitions)
openAPISpecs = append(openAPISpecs, spec)
openAPISpec.Definitions = handler.PruneDefaults(openAPISpec.Definitions)
openAPISpecs = append(openAPISpecs, openAPISpec)
}

if vwGroupManager == nil && server.GenericAPIServer.DiscoveryGroupManager != nil {
Expand Down
8 changes: 4 additions & 4 deletions pkg/virtual/framework/internalapis/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ func TestImportInternalAPIs(t *testing.T) {
apisToImport...)
require.NoError(t, err)
require.Len(t, schemas, 3)
for _, schema := range schemas {
expectedContent, err := embeddedResources.ReadFile(path.Join("fixtures", schema.Spec.Names.Plural+".yaml"))
for _, s := range schemas {
expectedContent, err := embeddedResources.ReadFile(path.Join("fixtures", s.Spec.Names.Plural+".yaml"))
require.NoError(t, err)
actualContent, err := yaml.Marshal(schema)
actualContent, err := yaml.Marshal(s)
require.NoError(t, err)
require.Emptyf(t, cmp.Diff(strings.Split(string(expectedContent), "\n"), strings.Split(string(actualContent), "\n")), "%s was not identical to the expected content", schema.Name)
require.Emptyf(t, cmp.Diff(strings.Split(string(expectedContent), "\n"), strings.Split(string(actualContent), "\n")), "%s was not identical to the expected content", s.Name)
}
}
6 changes: 3 additions & 3 deletions pkg/virtual/initializingworkspaces/builder/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,18 +342,18 @@ func digestUrl(urlPath, rootPathPrefix string) (

withoutClustersPrefix := strings.TrimPrefix(realPath, "/clusters/")
parts = strings.SplitN(withoutClustersPrefix, "/", 2)
path := logicalcluster.NewPath(parts[0])
logicalclusterPath := logicalcluster.NewPath(parts[0])
realPath = "/"
if len(parts) > 1 {
realPath += parts[1]
}

cluster = genericapirequest.Cluster{}
if path == logicalcluster.Wildcard {
if logicalclusterPath == logicalcluster.Wildcard {
cluster.Wildcard = true
} else {
var ok bool
cluster.Name, ok = path.Name()
cluster.Name, ok = logicalclusterPath.Name()
if !ok {
return genericapirequest.Cluster{}, "", "", false
}
Expand Down
Loading

0 comments on commit 5342cf0

Please sign in to comment.