Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(k8s): implement wildcard All Namespaces discovery #725

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
99 changes: 78 additions & 21 deletions src/main/java/io/cryostat/discovery/KubeApiDiscovery.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.management.remote.JMXServiceURL;

Expand Down Expand Up @@ -108,26 +109,38 @@ public class KubeApiDiscovery implements ResourceEventHandler<Endpoints> {
@Override
protected HashMap<String, SharedIndexInformer<Endpoints>> initialize()
throws ConcurrentException {
// TODO: add support for some wildcard indicating a single Informer for any
// namespace that Cryostat has permissions to. This will need some restructuring
// of how the namespaces within the discovery tree are mapped.
var result = new HashMap<String, SharedIndexInformer<Endpoints>>();
kubeConfig
.getWatchNamespaces()
.forEach(
ns -> {
result.put(
ns,
client.endpoints()
.inNamespace(ns)
.inform(
KubeApiDiscovery.this,
informerResyncPeriod.toMillis()));
logger.debugv(
"Started Endpoints SharedInformer for namespace"
+ " \"{0}\" with resync period {1}",
ns, informerResyncPeriod);
});
if (kubeConfig.watchAllNamespaces()) {
result.put(
KubeConfig.ALL_NAMESPACES,
client.endpoints()
.inAnyNamespace()
.inform(
KubeApiDiscovery.this,
informerResyncPeriod.toMillis()));
Copy link
Member

Choose a reason for hiding this comment

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

Maybe, add a logger.debugv here?

 logger.debugv(
        "Started Endpoints SharedInformer for all namespace with resync period {0}",
        informerResyncPeriod);

logger.debugv(
"Started Endpoints Informer for All Namespaces with resync period"
+ " {0}",
informerResyncPeriod);
} else {
kubeConfig
.getWatchNamespaces()
.forEach(
ns -> {
result.put(
ns,
client.endpoints()
.inNamespace(ns)
.inform(
KubeApiDiscovery.this,
informerResyncPeriod
.toMillis()));
logger.debugv(
"Started Endpoints SharedInformer for namespace"
+ " \"{0}\" with resync period {1}",
ns, informerResyncPeriod);
});
}
return result;
}
};
Expand All @@ -144,11 +157,13 @@ void onStart(@Observes StartupEvent evt) {

logger.debugv("Starting {0} client", REALM);
safeGetInformers();
// TODO we should not need to force manual re-syncs this way - the Informer is already
// supposed to resync itself.
Comment on lines +160 to +161
Copy link
Member

Choose a reason for hiding this comment

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

Just curious here: Is it now safe to remove this manual resync? If not, in the case of all namespaces, we should also list namespaces and do resync too?

resyncWorker.scheduleAtFixedRate(
() -> {
try {
logger.debug("Resyncing");
notify(NamespaceQueryEvent.from(kubeConfig.getWatchNamespaces()));
notify(NamespaceQueryEvent.from(getWatchNamespaces()));
} catch (Exception e) {
logger.warn(e);
}
Expand All @@ -158,6 +173,17 @@ void onStart(@Observes StartupEvent evt) {
TimeUnit.MILLISECONDS);
}

private List<String> getWatchNamespaces() {
if (kubeConfig.watchAllNamespaces()) {
return client.namespaces().list().getItems().stream()
.map(ns -> ns.getMetadata().getName())
.toList();
}
return kubeConfig.getWatchNamespaces().stream()
.filter(ns -> !KubeConfig.ALL_NAMESPACES.equals(ns))
.toList();
}

void onStop(@Observes ShutdownEvent evt) {
if (!(enabled() && available())) {
return;
Expand Down Expand Up @@ -226,6 +252,15 @@ List<TargetTuple> tuplesFromEndpoints(Endpoints endpoints) {
for (EndpointPort port : subset.getPorts()) {
for (EndpointAddress addr : subset.getAddresses()) {
var ref = addr.getTargetRef();
if (ref == null) {
logger.debugv(
"Endpoints object {0} in {1} with address {2} had a null"
+ " targetRef",
endpoints.getMetadata().getName(),
endpoints.getMetadata().getNamespace(),
addr.getIp());
continue;
}
tts.add(
new TargetTuple(
ref,
Expand Down Expand Up @@ -295,8 +330,24 @@ public void handleQueryEvent(NamespaceQueryEvent evt) {
persistedTargets.add(node.target);
}

Stream<Endpoints> endpoints;
if (kubeConfig.watchAllNamespaces()) {
endpoints =
safeGetInformers()
.get(KubeConfig.ALL_NAMESPACES)
.getStore()
.list()
.stream()
.filter(
ep ->
Objects.equals(
ep.getMetadata().getNamespace(),
namespace));
} else {
endpoints = safeGetInformers().get(namespace).getStore().list().stream();
}
Set<Target> observedTargets =
safeGetInformers().get(namespace).getStore().list().stream()
endpoints
.map((endpoint) -> getTargetTuplesFrom(endpoint))
.flatMap(List::stream)
.filter((tuple) -> Objects.nonNull(tuple.objRef))
Expand Down Expand Up @@ -533,6 +584,7 @@ private Pair<HasMetadata, DiscoveryNode> queryForNode(

@ApplicationScoped
static final class KubeConfig {
static final String ALL_NAMESPACES = "*";
private static final String OWN_NAMESPACE = ".";

@Inject Logger logger;
Expand All @@ -547,6 +599,11 @@ static final class KubeConfig {
@ConfigProperty(name = "cryostat.discovery.kubernetes.namespace-path")
String namespacePath;

boolean watchAllNamespaces() {
return watchNamespaces.orElse(List.of()).stream()
.anyMatch(ns -> ALL_NAMESPACES.equals(ns));
}

Collection<String> getWatchNamespaces() {
return watchNamespaces.orElse(List.of()).stream()
.map(
Expand Down
Loading