Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(crd-generator): Fix processing private and package-private CustomResource classes #6686

Merged
merged 2 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
Expand Down Expand Up @@ -165,7 +168,7 @@ public String[] labels() {

public static CustomResourceInfo fromClass(Class<? extends HasMetadata> customResource) {
try {
final HasMetadata instance = customResource.getDeclaredConstructor().newInstance();
final HasMetadata instance = createInstance(customResource);

final String[] shortNames = CustomResource.getShortNames(customResource);
final String[] categories = CustomResource.getCategories(customResource);
Expand Down Expand Up @@ -203,11 +206,40 @@ public static CustomResourceInfo fromClass(Class<? extends HasMetadata> customRe
customResource.getCanonicalName(), specAndStatus.getSpecClassName(),
specAndStatus.getStatusClassName(), toStringArray(instance.getMetadata().getAnnotations()),
toStringArray(instance.getMetadata().getLabels()));
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw KubernetesClientException.launderThrowable(e);
}
}

private static HasMetadata createInstance(Class<? extends HasMetadata> customResource)
throws InvocationTargetException, InstantiationException, IllegalAccessException {
final Constructor<?> defaultConstructor = Arrays.stream(customResource.getDeclaredConstructors())
.filter(constructor -> constructor.getParameterCount() == 0)
.findFirst()
.orElseThrow(() -> new IllegalStateException(
"Cannot find default constructor for " + customResource.getCanonicalName()));

if (Modifier.isPublic(customResource.getModifiers())
&& Modifier.isPublic(defaultConstructor.getModifiers())) {
return (HasMetadata) defaultConstructor.newInstance();
}

LOGGER.trace(
"Default constructor for CustomResource class {} is not accessible. Modifying accessibility...",
customResource.getCanonicalName());

boolean accessible = defaultConstructor.trySetAccessible();
if (!accessible) {
LOGGER.warn(
"Default constructor for CustomResource class {} is not accessible.",
customResource.getCanonicalName());
} else {
LOGGER.debug(
"Modified constructor for CustomResource class {} to make it accessible.", customResource.getCanonicalName());
}
return (HasMetadata) defaultConstructor.newInstance();
}

public static String[] toStringArray(Map<String, String> map) {
String[] res = new String[map.size()];
Set<Map.Entry<String, String>> entrySet = map.entrySet();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class CustomResourceInfoTest {
Expand All @@ -44,12 +46,33 @@ public static class Status {
@Version(VERSION)
@ShortNames("s")
@Categories("cat")
public static class ClusteredCR extends CustomResource<Spec, Status> {
public static class ClusteredCR extends
io.fabric8.kubernetes.client.CustomResource<Spec, Status> {
}

@Group(GROUP)
@Version(VERSION)
public static class NamespacedCR extends CustomResource<Spec, Status> implements Namespaced {
public static class NamespacedCR extends io.fabric8.kubernetes.client.CustomResource<Spec, Status>
implements Namespaced {
}

@Group(GROUP)
@Version(VERSION)
static class PackagePrivateInnerCustomResource extends
io.fabric8.kubernetes.client.CustomResource<Void, Void> {
}

@Group(GROUP)
@Version(VERSION)
private static class PrivateInnerCustomResource extends
io.fabric8.kubernetes.client.CustomResource<Void, Void> {
}

@Group(GROUP)
@Version(VERSION)
private static class NoDefaultConstructorCustomResource extends CustomResource<Void, Void> {
NoDefaultConstructorCustomResource(String s) {
}
}

@Test
Expand Down Expand Up @@ -92,4 +115,22 @@ void shouldProperlyCreateCustomResourceInfo() {
assertTrue(info.storage());
assertEquals(HasMetadata.getKind(ClusteredCR.class), info.kind());
}

@Test
void shouldCreateCustomResourceInfoFromPackagePrivateClass() {
CustomResourceInfo info = CustomResourceInfo.fromClass(PackagePrivateInnerCustomResource.class);
assertNotNull(info);
}

@Test
void shouldCreateCustomResourceInfoFromPrivateClass() {
CustomResourceInfo info = CustomResourceInfo.fromClass(PrivateInnerCustomResource.class);
assertNotNull(info);
}

@Test
void shouldFailForMissingDefaultConstructor() {
assertThrows(IllegalStateException.class,
() -> CustomResourceInfo.fromClass(NoDefaultConstructorCustomResource.class));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Fabric8 CRDGenerator, manual edits might get overwritten!
apiVersion: "apiextensions.k8s.io/v1"
kind: "CustomResourceDefinition"
metadata:
name: "packageprivatecustomresources.sample.fabric8.io"
spec:
group: "sample.fabric8.io"
names:
kind: "PackagePrivateCustomResource"
plural: "packageprivatecustomresources"
singular: "packageprivatecustomresource"
scope: "Cluster"
versions:
- name: "v1"
schema:
openAPIV3Schema:
properties:
spec:
type: "object"
status:
type: "object"
type: "object"
served: true
storage: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Fabric8 CRDGenerator, manual edits might get overwritten!
apiVersion: "apiextensions.k8s.io/v1"
kind: "CustomResourceDefinition"
metadata:
name: "packageprivateinnercustomresources.sample.fabric8.io"
spec:
group: "sample.fabric8.io"
names:
kind: "PackagePrivateInnerCustomResource"
plural: "packageprivateinnercustomresources"
singular: "packageprivateinnercustomresource"
scope: "Cluster"
versions:
- name: "v1"
schema:
openAPIV3Schema:
properties:
spec:
type: "object"
status:
type: "object"
type: "object"
served: true
storage: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Fabric8 CRDGenerator, manual edits might get overwritten!
apiVersion: "apiextensions.k8s.io/v1"
kind: "CustomResourceDefinition"
metadata:
name: "privateinnercustomresources.sample.fabric8.io"
spec:
group: "sample.fabric8.io"
names:
kind: "PrivateInnerCustomResource"
plural: "privateinnercustomresources"
singular: "privateinnercustomresource"
scope: "Cluster"
versions:
- name: "v1"
schema:
openAPIV3Schema:
properties:
spec:
type: "object"
status:
type: "object"
type: "object"
served: true
storage: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Fabric8 CRDGenerator, manual edits might get overwritten!
apiVersion: "apiextensions.k8s.io/v1"
kind: "CustomResourceDefinition"
metadata:
name: "publicinnercustomresources.sample.fabric8.io"
spec:
group: "sample.fabric8.io"
names:
kind: "PublicInnerCustomResource"
plural: "publicinnercustomresources"
singular: "publicinnercustomresource"
scope: "Cluster"
versions:
- name: "v1"
schema:
openAPIV3Schema:
properties:
spec:
type: "object"
status:
type: "object"
type: "object"
served: true
storage: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.crd.maven.example;

import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;

public class InnerResources {

@Group("sample.fabric8.io")
@Version(value = "v1")
public static class PublicInnerCustomResource extends CustomResource<Void, Void> {
}

@Group("sample.fabric8.io")
@Version(value = "v1")
static class PackagePrivateInnerCustomResource extends CustomResource<Void, Void> {
}

@Group("sample.fabric8.io")
@Version(value = "v1")
private static class PrivateInnerCustomResource extends CustomResource<Void, Void> {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.crd.maven.example;

import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;

@Group("sample.fabric8.io")
@Version(value = "v1")
class PackagePrivateCustomResource extends CustomResource<Void, Void> {
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ Path basedirPath = basedir.toPath();


[
"multiples.sample.fabric8.io-v1"
"multiples.sample.fabric8.io-v1",
"packageprivatecustomresources.sample.fabric8.io-v1",
"packageprivateinnercustomresources.sample.fabric8.io-v1",
"privateinnercustomresources.sample.fabric8.io-v1",
"publicinnercustomresources.sample.fabric8.io-v1"
].each {
Verify.verifyContentEquals(
basedirPath.resolve(Paths.get("target", "classes", "META-INF", "fabric8", it + ".yml")),
Expand Down
Loading