/**
* POST TITLE: Cilium eBPF Networking Integration in Java
*
* Complete implementation of Cilium eBPF networking features in Java applications
*/
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.Resource;
import java.util.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.util.concurrent.*;
public class CiliumeBPFIntegration {
/**
* Cilium Network Policy Manager
*/
public static class CiliumNetworkPolicyManager {
private final KubernetesClient client;
private final String namespace;
public CiliumNetworkPolicyManager(KubernetesClient client, String namespace) {
this.client = client;
this.namespace = namespace;
}
/**
* Cilium Network Policy Definition
*/
public static class CiliumNetworkPolicy {
private String name;
private List<EndpointSelector> endpointSelectors;
private List<IngressRule> ingress;
private List<EgressRule> egress;
private Map<String, String> labels;
public CiliumNetworkPolicy(String name) {
this.name = name;
this.endpointSelectors = new ArrayList<>();
this.ingress = new ArrayList<>();
this.egress = new ArrayList<>();
this.labels = new HashMap<>();
}
// Builder methods
public CiliumNetworkPolicy withEndpointSelector(Map<String, String> matchLabels) {
this.endpointSelectors.add(new EndpointSelector(matchLabels));
return this;
}
public CiliumNetworkPolicy withIngressRule(IngressRule rule) {
this.ingress.add(rule);
return this;
}
public CiliumNetworkPolicy withEgressRule(EgressRule rule) {
this.egress.add(rule);
return this;
}
public CiliumNetworkPolicy withLabel(String key, String value) {
this.labels.put(key, value);
return this;
}
// Getters
public String getName() { return name; }
public List<EndpointSelector> getEndpointSelectors() { return endpointSelectors; }
public List<IngressRule> getIngress() { return ingress; }
public List<EgressRule> getEgress() { return egress; }
public Map<String, String> getLabels() { return labels; }
}
public static class EndpointSelector {
private Map<String, String> matchLabels;
public EndpointSelector(Map<String, String> matchLabels) {
this.matchLabels = matchLabels;
}
public Map<String, String> getMatchLabels() { return matchLabels; }
}
public static class IngressRule {
private List<EndpointSelector> fromEndpoints;
private List<PortRule> toPorts;
private List<CIDRRule> fromCIDR;
public IngressRule() {
this.fromEndpoints = new ArrayList<>();
this.toPorts = new ArrayList<>();
this.fromCIDR = new ArrayList<>();
}
// Builder methods
public IngressRule fromEndpoint(Map<String, String> matchLabels) {
this.fromEndpoints.add(new EndpointSelector(matchLabels));
return this;
}
public IngressRule toPort(int port, String protocol) {
this.toPorts.add(new PortRule(port, protocol));
return this;
}
public IngressRule fromCIDR(String cidr) {
this.fromCIDR.add(new CIDRRule(cidr));
return this;
}
// Getters
public List<EndpointSelector> getFromEndpoints() { return fromEndpoints; }
public List<PortRule> getToPorts() { return toPorts; }
public List<CIDRRule> getFromCIDR() { return fromCIDR; }
}
public static class EgressRule {
private List<EndpointSelector> toEndpoints;
private List<PortRule> toPorts;
private List<CIDRRule> toCIDR;
public EgressRule() {
this.toEndpoints = new ArrayList<>();
this.toPorts = new ArrayList<>();
this.toCIDR = new ArrayList<>();
}
// Builder methods
public EgressRule toEndpoint(Map<String, String> matchLabels) {
this.toEndpoints.add(new EndpointSelector(matchLabels));
return this;
}
public EgressRule toPort(int port, String protocol) {
this.toPorts.add(new PortRule(port, protocol));
return this;
}
public EgressRule toCIDR(String cidr) {
this.toCIDR.add(new CIDRRule(cidr));
return this;
}
// Getters
public List<EndpointSelector> getToEndpoints() { return toEndpoints; }
public List<PortRule> getToPorts() { return toPorts; }
public List<CIDRRule> getToCIDR() { return toCIDR; }
}
public static class PortRule {
private int port;
private String protocol;
public PortRule(int port, String protocol) {
this.port = port;
this.protocol = protocol;
}
public int getPort() { return port; }
public String getProtocol() { return protocol; }
}
public static class CIDRRule {
private String cidr;
public CIDRRule(String cidr) {
this.cidr = cidr;
}
public String getCidr() { return cidr; }
}
/**
* Create Cilium Network Policy
*/
public void createNetworkPolicy(CiliumNetworkPolicy policy) {
try {
// Convert to Kubernetes Custom Resource
Map<String, Object> policySpec = buildPolicySpec(policy);
CustomResourceDefinitionContext context = new CustomResourceDefinitionContext.Builder()
.withGroup("cilium.io")
.withVersion("v2")
.withPlural("ciliumnetworkpolicies")
.withScope("Namespaced")
.build();
Map<String, Object> policyResource = Map.of(
"apiVersion", "cilium.io/v2",
"kind", "CiliumNetworkPolicy",
"metadata", Map.of(
"name", policy.getName(),
"namespace", namespace,
"labels", policy.getLabels()
),
"spec", policySpec
);
client.customResource(context).create(namespace, policyResource);
System.out.println("β
Created CiliumNetworkPolicy: " + policy.getName());
} catch (Exception e) {
System.err.println("β Failed to create CiliumNetworkPolicy: " + e.getMessage());
throw new RuntimeException("Policy creation failed", e);
}
}
private Map<String, Object> buildPolicySpec(CiliumNetworkPolicy policy) {
Map<String, Object> spec = new HashMap<>();
// Endpoint selectors
if (!policy.getEndpointSelectors().isEmpty()) {
List<Map<String, Object>> endpointSelectors = new ArrayList<>();
for (EndpointSelector selector : policy.getEndpointSelectors()) {
endpointSelectors.add(Map.of("matchLabels", selector.getMatchLabels()));
}
spec.put("endpointSelector", endpointSelectors.get(0)); // Cilium uses single endpointSelector
}
// Ingress rules
if (!policy.getIngress().isEmpty()) {
List<Map<String, Object>> ingressRules = new ArrayList<>();
for (IngressRule rule : policy.getIngress()) {
Map<String, Object> ingressRule = new HashMap<>();
if (!rule.getFromEndpoints().isEmpty()) {
List<Map<String, Object>> fromEndpoints = new ArrayList<>();
for (EndpointSelector selector : rule.getFromEndpoints()) {
fromEndpoints.add(Map.of("matchLabels", selector.getMatchLabels()));
}
ingressRule.put("fromEndpoints", fromEndpoints);
}
if (!rule.getToPorts().isEmpty()) {
List<Map<String, Object>> toPorts = new ArrayList<>();
for (PortRule portRule : rule.getToPorts()) {
toPorts.add(Map.of(
"ports", List.of(Map.of(
"port", String.valueOf(portRule.getPort()),
"protocol", portRule.getProtocol()
))
));
}
ingressRule.put("toPorts", toPorts);
}
if (!rule.getFromCIDR().isEmpty()) {
List<String> fromCIDR = new ArrayList<>();
for (CIDRRule cidrRule : rule.getFromCIDR()) {
fromCIDR.add(cidrRule.getCidr());
}
ingressRule.put("fromCIDR", fromCIDR);
}
ingressRules.add(ingressRule);
}
spec.put("ingress", ingressRules);
}
// Egress rules
if (!policy.getEgress().isEmpty()) {
List<Map<String, Object>> egressRules = new ArrayList<>();
for (EgressRule rule : policy.getEgress()) {
Map<String, Object> egressRule = new HashMap<>();
if (!rule.getToEndpoints().isEmpty()) {
List<Map<String, Object>> toEndpoints = new ArrayList<>();
for (EndpointSelector selector : rule.getToEndpoints()) {
toEndpoints.add(Map.of("matchLabels", selector.getMatchLabels()));
}
egressRule.put("toEndpoints", toEndpoints);
}
if (!rule.getToPorts().isEmpty()) {
List<Map<String, Object>> toPorts = new ArrayList<>();
for (PortRule portRule : rule.getToPorts()) {
toPorts.add(Map.of(
"ports", List.of(Map.of(
"port", String.valueOf(portRule.getPort()),
"protocol", portRule.getProtocol()
))
));
}
egressRule.put("toPorts", toPorts);
}
if (!rule.getToCIDR().isEmpty()) {
List<String> toCIDR = new ArrayList<>();
for (CIDRRule cidrRule : rule.getToCIDR()) {
toCIDR.add(cidrRule.getCidr());
}
egressRule.put("toCIDR", toCIDR);
}
egressRules.add(egressRule);
}
spec.put("egress", egressRules);
}
return spec;
}
/**
* Create sample policies for common scenarios
*/
public void createWebApplicationPolicy(String appName) {
CiliumNetworkPolicy policy = new CiliumNetworkPolicy(appName + "-web-policy")
.withEndpointSelector(Map.of("app", appName))
.withLabel("policy-type", "web-application")
.withIngressRule(new IngressRule()
.fromEndpoint(Map.of("app", "ingress-controller"))
.toPort(8080, "TCP"))
.withIngressRule(new IngressRule()
.fromCIDR("10.0.0.0/8")
.toPort(8080, "TCP"))
.withEgressRule(new EgressRule()
.toEndpoint(Map.of("app", "database"))
.toPort(5432, "TCP"))
.withEgressRule(new EgressRule()
.toCIDR("0.0.0.0/0")
.toPort(53, "UDP"));
createNetworkPolicy(policy);
}
public void createDatabasePolicy(String dbName) {
CiliumNetworkPolicy policy = new CiliumNetworkPolicy(dbName + "-db-policy")
.withEndpointSelector(Map.of("app", dbName))
.withLabel("policy-type", "database")
.withIngressRule(new IngressRule()
.fromEndpoint(Map.of("app", "web-application"))
.toPort(5432, "TCP"))
.withEgressRule(new EgressRule()
.toCIDR("0.0.0.0/0")
.toPort(53, "UDP"));
createNetworkPolicy(policy);
}
public void createMultiTierApplicationPolicy() {
// Frontend policy
createNetworkPolicy(new CiliumNetworkPolicy("frontend-policy")
.withEndpointSelector(Map.of("tier", "frontend"))
.withIngressRule(new IngressRule()
.fromCIDR("0.0.0.0/0")
.toPort(80, "TCP")
.toPort(443, "TCP"))
.withEgressRule(new EgressRule()
.toEndpoint(Map.of("tier", "backend"))
.toPort(8080, "TCP")));
// Backend policy
createNetworkPolicy(new CiliumNetworkPolicy("backend-policy")
.withEndpointSelector(Map.of("tier", "backend"))
.withIngressRule(new IngressRule()
.fromEndpoint(Map.of("tier", "frontend"))
.toPort(8080, "TCP"))
.withEgressRule(new EgressRule()
.toEndpoint(Map.of("tier", "database"))
.toPort(5432, "TCP")));
// Database policy
createNetworkPolicy(new CiliumNetworkPolicy("database-policy")
.withEndpointSelector(Map.of("tier", "database"))
.withIngressRule(new IngressRule()
.fromEndpoint(Map.of("tier", "backend"))
.toPort(5432, "TCP")));
}
}
/**
* Cilium Hubble Client for Network Observability
*/
public static class CiliumHubbleClient {
private final String hubbleUrl;
private final HttpClient httpClient;
public CiliumHubbleClient(String hubbleUrl) {
this.hubbleUrl = hubbleUrl;
this.httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build();
}
/**
* Flow data structure
*/
public static class Flow {
private String source;
private String destination;
private String verdict;
private String l4Protocol;
private int sourcePort;
private int destinationPort;
private Date timestamp;
private String eventType;
public Flow(String source, String destination, String verdict,
String l4Protocol, int sourcePort, int destinationPort) {
this.source = source;
this.destination = destination;
this.verdict = verdict;
this.l4Protocol = l4Protocol;
this.sourcePort = sourcePort;
this.destinationPort = destinationPort;
this.timestamp = new Date();
}
// Getters
public String getSource() { return source; }
public String getDestination() { return destination; }
public String getVerdict() { return verdict; }
public String getL4Protocol() { return l4Protocol; }
public int getSourcePort() { return sourcePort; }
public int getDestinationPort() { return destinationPort; }
public Date getTimestamp() { return timestamp; }
public String getEventType() { return eventType; }
}
/**
* Get flows for a specific pod
*/
public List<Flow> getFlowsForPod(String namespace, String podName) {
try {
String url = String.format("%s/api/v1/flows?source_pod=%s/%s",
hubbleUrl, namespace, podName);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
return parseFlowsResponse(response.body());
} catch (Exception e) {
System.err.println("β Failed to get flows: " + e.getMessage());
return Collections.emptyList();
}
}
/**
* Get denied flows (security events)
*/
public List<Flow> getDeniedFlows(String namespace) {
try {
String url = String.format("%s/api/v1/flows?verdict=DENIED&namespace=%s",
hubbleUrl, namespace);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
return parseFlowsResponse(response.body());
} catch (Exception e) {
System.err.println("β Failed to get denied flows: " + e.getMessage());
return Collections.emptyList();
}
}
/**
* Get service map
*/
public Map<String, List<String>> getServiceMap() {
try {
String url = hubbleUrl + "/api/v1/service-map";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
return parseServiceMapResponse(response.body());
} catch (Exception e) {
System.err.println("β Failed to get service map: " + e.getMessage());
return Collections.emptyMap();
}
}
private List<Flow> parseFlowsResponse(String jsonResponse) {
// Simplified parsing - in production use Jackson/Gson
List<Flow> flows = new ArrayList<>();
// Mock data for demonstration
flows.add(new Flow("10.0.1.5", "10.0.2.10", "ALLOWED", "TCP", 34567, 8080));
flows.add(new Flow("10.0.1.6", "10.0.2.10", "DENIED", "TCP", 45678, 8080));
flows.add(new Flow("10.0.2.10", "10.0.3.5", "ALLOWED", "TCP", 56789, 5432));
return flows;
}
private Map<String, List<String>> parseServiceMapResponse(String jsonResponse) {
// Simplified parsing
Map<String, List<String>> serviceMap = new HashMap<>();
serviceMap.put("frontend-service", Arrays.asList("10.0.1.5", "10.0.1.6"));
serviceMap.put("backend-service", Arrays.asList("10.0.2.10", "10.0.2.11"));
serviceMap.put("database-service", Arrays.asList("10.0.3.5"));
return serviceMap;
}
/**
* Real-time flow monitoring
*/
public void startFlowMonitoring(String namespace, FlowListener listener) {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
List<Flow> recentFlows = getFlowsForPod(namespace, "all");
for (Flow flow : recentFlows) {
listener.onFlow(flow);
}
}, 0, 5, TimeUnit.SECONDS); // Poll every 5 seconds
}
public interface FlowListener {
void onFlow(Flow flow);
}
}
/**
* eBPF-based Service Mesh Integration
*/
public static class CiliumServiceMesh {
private final KubernetesClient client;
private final CiliumHubbleClient hubbleClient;
public CiliumServiceMesh(KubernetesClient client, String hubbleUrl) {
this.client = client;
this.hubbleClient = new CiliumHubbleClient(hubbleUrl);
}
/**
* Service-to-service communication metrics
*/
public static class ServiceMetrics {
private String sourceService;
private String destinationService;
private long requestCount;
private long errorCount;
private double averageLatency;
private Map<Integer, Long> responseCodes;
public ServiceMetrics(String sourceService, String destinationService) {
this.sourceService = sourceService;
this.destinationService = destinationService;
this.requestCount = 0;
this.errorCount = 0;
this.averageLatency = 0.0;
this.responseCodes = new HashMap<>();
}
// Getters and setters
public String getSourceService() { return sourceService; }
public String getDestinationService() { return destinationService; }
public long getRequestCount() { return requestCount; }
public void setRequestCount(long requestCount) { this.requestCount = requestCount; }
public long getErrorCount() { return errorCount; }
public void setErrorCount(long errorCount) { this.errorCount = errorCount; }
public double getAverageLatency() { return averageLatency; }
public void setAverageLatency(double averageLatency) { this.averageLatency = averageLatency; }
public Map<Integer, Long> getResponseCodes() { return responseCodes; }
}
/**
* Get service metrics from Hubble
*/
public Map<String, ServiceMetrics> getServiceMetrics(String namespace) {
Map<String, ServiceMetrics> metrics = new HashMap<>();
List<CiliumHubbleClient.Flow> flows = hubbleClient.getFlowsForPod(namespace, "all");
for (CiliumHubbleClient.Flow flow : flows) {
String key = flow.getSource() + "->" + flow.getDestination();
ServiceMetrics metric = metrics.getOrDefault(key,
new ServiceMetrics(flow.getSource(), flow.getDestination()));
metric.setRequestCount(metric.getRequestCount() + 1);
if ("DENIED".equals(flow.getVerdict())) {
metric.setErrorCount(metric.getErrorCount() + 1);
}
metrics.put(key, metric);
}
return metrics;
}
/**
* Detect network anomalies
*/
public List<String> detectAnomalies(String namespace) {
List<String> anomalies = new ArrayList<>();
Map<String, ServiceMetrics> metrics = getServiceMetrics(namespace);
for (ServiceMetrics metric : metrics.values()) {
double errorRate = (double) metric.getErrorCount() / metric.getRequestCount();
if (errorRate > 0.1) { // 10% error rate threshold
anomalies.add(String.format(
"High error rate between %s and %s: %.2f%%",
metric.getSourceService(), metric.getDestinationService(),
errorRate * 100
));
}
if (metric.getRequestCount() > 1000) { // High traffic threshold
anomalies.add(String.format(
"High traffic volume between %s and %s: %d requests",
metric.getSourceService(), metric.getDestinationService(),
metric.getRequestCount()
));
}
}
return anomalies;
}
/**
* Generate network topology
*/
public Map<String, Set<String>> generateNetworkTopology(String namespace) {
Map<String, Set<String>> topology = new HashMap<>();
List<CiliumHubbleClient.Flow> flows = hubbleClient.getFlowsForPod(namespace, "all");
for (CiliumHubbleClient.Flow flow : flows) {
if ("ALLOWED".equals(flow.getVerdict())) {
topology.computeIfAbsent(flow.getSource(), k -> new HashSet<>())
.add(flow.getDestination());
}
}
return topology;
}
}
/**
* Security Policy Enforcer
*/
public static class CiliumSecurityEnforcer {
private final CiliumNetworkPolicyManager policyManager;
private final CiliumHubbleClient hubbleClient;
public CiliumSecurityEnforcer(KubernetesClient client, String namespace, String hubbleUrl) {
this.policyManager = new CiliumNetworkPolicyManager(client, namespace);
this.hubbleClient = new CiliumHubbleClient(hubbleUrl);
}
/**
* Auto-generate policies based on observed traffic
*/
public void generatePoliciesFromTraffic(String appName, int observationPeriodMinutes) {
System.out.println("π Observing traffic for " + observationPeriodMinutes + " minutes...");
// Collect flows during observation period
List<CiliumHubbleClient.Flow> observedFlows = new ArrayList<>();
CiliumHubbleClient.FlowListener listener = observedFlows::add;
hubbleClient.startFlowMonitoring("default", listener);
try {
Thread.sleep(observationPeriodMinutes * 60 * 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Analyze flows and generate policy
CiliumNetworkPolicyManager.CiliumNetworkPolicy policy =
analyzeFlowsAndCreatePolicy(appName, observedFlows);
policyManager.createNetworkPolicy(policy);
System.out.println("β
Generated policy from observed traffic: " + policy.getName());
}
private CiliumNetworkPolicyManager.CiliumNetworkPolicy analyzeFlowsAndCreatePolicy(
String appName, List<CiliumHubbleClient.Flow> flows) {
CiliumNetworkPolicyManager.CiliumNetworkPolicy policy =
new CiliumNetworkPolicyManager.CiliumNetworkPolicy(appName + "-auto-generated");
Set<String> allowedSources = new HashSet<>();
Set<Integer> allowedPorts = new HashSet<>();
for (CiliumHubbleClient.Flow flow : flows) {
if ("ALLOWED".equals(flow.getVerdict())) {
allowedSources.add(flow.getSource());
allowedPorts.add(flow.getDestinationPort());
}
}
// Create ingress rules
CiliumNetworkPolicyManager.IngressRule ingressRule =
new CiliumNetworkPolicyManager.IngressRule();
for (String source : allowedSources) {
if (source.startsWith("10.")) { // Internal IP
ingressRule.fromCIDR(source + "/32");
}
}
for (int port : allowedPorts) {
ingressRule.toPort(port, "TCP");
}
policy.withEndpointSelector(Map.of("app", appName))
.withIngressRule(ingressRule)
.withLabel("generated-by", "auto-policy")
.withLabel("app", appName);
return policy;
}
/**
* Enforce zero-trust network policy
*/
public void enforceZeroTrustPolicy(String appName) {
CiliumNetworkPolicyManager.CiliumNetworkPolicy policy =
new CiliumNetworkPolicyManager.CiliumNetworkPolicy(appName + "-zero-trust")
.withEndpointSelector(Map.of("app", appName))
.withLabel("security-level", "zero-trust")
// Default deny all
.withIngressRule(new CiliumNetworkPolicyManager.IngressRule()) // Empty rule = deny all
.withEgressRule(new CiliumNetworkPolicyManager.EgressRule()); // Empty rule = deny all
policyManager.createNetworkPolicy(policy);
System.out.println("π Enforced zero-trust policy for: " + appName);
}
}
/**
* Demo and Usage Examples
*/
public static void main(String[] args) {
System.out.println("π· Cilium eBPF Networking Java Integration");
System.out.println("==========================================\n");
try (KubernetesClient client = new KubernetesClientBuilder().build()) {
String namespace = "default";
String hubbleUrl = "http://localhost:8085";
// Initialize managers
CiliumNetworkPolicyManager policyManager =
new CiliumNetworkPolicyManager(client, namespace);
CiliumHubbleClient hubbleClient = new CiliumHubbleClient(hubbleUrl);
CiliumServiceMesh serviceMesh = new CiliumServiceMesh(client, hubbleUrl);
CiliumSecurityEnforcer securityEnforcer =
new CiliumSecurityEnforcer(client, namespace, hubbleUrl);
// Demo 1: Create network policies
System.out.println("1. π Creating Network Policies");
policyManager.createWebApplicationPolicy("webapp");
policyManager.createDatabasePolicy("postgres");
policyManager.createMultiTierApplicationPolicy();
// Demo 2: Network observability
System.out.println("\n2. π Network Observability");
List<CiliumHubbleClient.Flow> flows = hubbleClient.getFlowsForPod(namespace, "webapp");
System.out.println("Recent flows for webapp:");
for (CiliumHubbleClient.Flow flow : flows) {
System.out.printf(" %s -> %s:%d [%s]%n",
flow.getSource(), flow.getDestination(),
flow.getDestinationPort(), flow.getVerdict());
}
// Demo 3: Service mesh metrics
System.out.println("\n3. π Service Mesh Metrics");
Map<String, CiliumServiceMesh.ServiceMetrics> metrics =
serviceMesh.getServiceMetrics(namespace);
for (CiliumServiceMesh.ServiceMetrics metric : metrics.values()) {
System.out.printf(" %s -> %s: %d requests, %d errors%n",
metric.getSourceService(), metric.getDestinationService(),
metric.getRequestCount(), metric.getErrorCount());
}
// Demo 4: Anomaly detection
System.out.println("\n4. π¨ Anomaly Detection");
List<String> anomalies = serviceMesh.detectAnomalies(namespace);
if (anomalies.isEmpty()) {
System.out.println(" No anomalies detected");
} else {
for (String anomaly : anomalies) {
System.out.println(" β οΈ " + anomaly);
}
}
// Demo 5: Network topology
System.out.println("\n5. πΈοΈ Network Topology");
Map<String, Set<String>> topology = serviceMesh.generateNetworkTopology(namespace);
for (Map.Entry<String, Set<String>> entry : topology.entrySet()) {
System.out.println(" " + entry.getKey() + " connects to:");
for (String destination : entry.getValue()) {
System.out.println(" - " + destination);
}
}
// Demo 6: Security enforcement
System.out.println("\n6. π Security Enforcement");
securityEnforcer.enforceZeroTrustPolicy("critical-app");
System.out.println("\nβ
Cilium eBPF Integration Demo Completed");
} catch (Exception e) {
System.err.println("β Demo failed: " + e.getMessage());
e.printStackTrace();
}
}
/**
* Spring Boot Integration
*/
@Configuration
@EnableScheduling
public static class CiliumConfiguration {
@Value("${cilium.hubble.url:http://localhost:8085}")
private String hubbleUrl;
@Bean
public KubernetesClient kubernetesClient() {
return new KubernetesClientBuilder().build();
}
@Bean
public CiliumNetworkPolicyManager ciliumNetworkPolicyManager(KubernetesClient client) {
return new CiliumNetworkPolicyManager(client, "default");
}
@Bean
public CiliumHubbleClient ciliumHubbleClient() {
return new CiliumHubbleClient(hubbleUrl);
}
@Bean
public CiliumServiceMesh ciliumServiceMesh(KubernetesClient client) {
return new CiliumServiceMesh(client, hubbleUrl);
}
@Bean
public CiliumSecurityEnforcer ciliumSecurityEnforcer(KubernetesClient client) {
return new CiliumSecurityEnforcer(client, "default", hubbleUrl);
}
}
/**
* Monitoring Service
*/
@Service
public static class NetworkMonitoringService {
private final CiliumServiceMesh serviceMesh;
private final CiliumHubbleClient hubbleClient;
public NetworkMonitoringService(CiliumServiceMesh serviceMesh,
CiliumHubbleClient hubbleClient) {
this.serviceMesh = serviceMesh;
this.hubbleClient = hubbleClient;
}
@Scheduled(fixedRate = 30000) // Every 30 seconds
public void monitorNetworkHealth() {
List<String> anomalies = serviceMesh.detectAnomalies("default");
if (!anomalies.isEmpty()) {
System.out.println("π¨ Network anomalies detected:");
for (String anomaly : anomalies) {
System.out.println(" - " + anomaly);
// In production, send to alerting system
}
}
}
@Scheduled(fixedRate = 60000) // Every minute
public void reportMetrics() {
Map<String, CiliumServiceMesh.ServiceMetrics> metrics =
serviceMesh.getServiceMetrics("default");
// Log or export metrics
System.out.println("π Network Metrics Report:");
for (CiliumServiceMesh.ServiceMetrics metric : metrics.values()) {
System.out.printf(" %s -> %s: %d req/s, %.2f%% error rate%n",
metric.getSourceService(), metric.getDestinationService(),
metric.getRequestCount() / 60, // req per second
((double) metric.getErrorCount() / metric.getRequestCount()) * 100);
}
}
}
}
Maven Dependencies
<!-- pom.xml --> <dependencies> <!-- Kubernetes Client --> <dependency> <groupId>io.fabric8</groupId> <artifactId>kubernetes-client</artifactId> <version>6.8.0</version> </dependency> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.7.0</version> </dependency> <!-- HTTP Client --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.3.20</version> </dependency> <!-- JSON Processing --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency> </dependencies>
Sample CiliumNetworkPolicy YAML
apiVersion: cilium.io/v2 kind: CiliumNetworkPolicy metadata: name: webapp-policy namespace: default spec: endpointSelector: matchLabels: app: webapp ingress: - fromEndpoints: - matchLabels: app: ingress-controller toPorts: - ports: - port: "8080" protocol: TCP - fromCIDR: - "10.0.0.0/8" toPorts: - ports: - port: "8080" protocol: TCP egress: - toEndpoints: - matchLabels: app: database toPorts: - ports: - port: "5432" protocol: TCP
This Cilium eBPF integration provides:
- Network Policy Management with Java DSL
- Hubble Observability integration for network flows
- Service Mesh Metrics collection and analysis
- Security Policy Enforcement with zero-trust principles
- Anomaly Detection for network security
- Automated Policy Generation from observed traffic
- Spring Boot Integration for production use
- Real-time Monitoring with scheduled tasks
The solution enables Java applications to leverage Cilium's eBPF-powered networking capabilities for security, observability, and service mesh functionality in Kubernetes environments.
Pyroscope Profiling in Java
Explains how to use Pyroscope for continuous profiling in Java applications, helping developers analyze CPU and memory usage patterns to improve performance and identify bottlenecks.
https://macronepal.com/blog/pyroscope-profiling-in-java/
OpenTelemetry Metrics in Java: Comprehensive Guide
Provides a complete guide to collecting and exporting metrics in Java using OpenTelemetry, including counters, histograms, gauges, and integration with monitoring tools. (MACRO NEPAL)
https://macronepal.com/blog/opentelemetry-metrics-in-java-comprehensive-guide/
OTLP Exporter in Java: Complete Guide for OpenTelemetry
Explains how to configure OTLP exporters in Java to send telemetry data such as traces, metrics, and logs to monitoring systems using HTTP or gRPC protocols. (MACRO NEPAL)
https://macronepal.com/blog/otlp-exporter-in-java-complete-guide-for-opentelemetry/
Thanos Integration in Java: Global View of Metrics
Explains how to integrate Thanos with Java monitoring systems to create a scalable global metrics view across multiple Prometheus instances.
https://macronepal.com/blog/thanos-integration-in-java-global-view-of-metrics
Time Series with InfluxDB in Java: Complete Guide (Version 2)
Explains how to manage time-series data using InfluxDB in Java applications, including storing, querying, and analyzing metrics data.
https://macronepal.com/blog/time-series-with-influxdb-in-java-complete-guide-2
Time Series with InfluxDB in Java: Complete Guide
Provides an overview of integrating InfluxDB with Java for time-series data handling, including monitoring applications and managing performance metrics.
https://macronepal.com/blog/time-series-with-influxdb-in-java-complete-guide
Implementing Prometheus Remote Write in Java (Version 2)
Explains how to configure Java applications to send metrics data to Prometheus-compatible systems using the remote write feature for scalable monitoring.
https://macronepal.com/blog/implementing-prometheus-remote-write-in-java-a-complete-guide-2
Implementing Prometheus Remote Write in Java: Complete Guide
Provides instructions for sending metrics from Java services to Prometheus servers, enabling centralized monitoring and real-time analytics.
https://macronepal.com/blog/implementing-prometheus-remote-write-in-java-a-complete-guide
Building a TileServer GL in Java: Vector and Raster Tile Server
Explains how to build a TileServer GL in Java for serving vector and raster map tiles, useful for geographic visualization and mapping applications.
https://macronepal.com/blog/building-a-tileserver-gl-in-java-vector-and-raster-tile-server
Indoor Mapping in Java
Explains how to create indoor mapping systems in Java, including navigation inside buildings, spatial data handling, and visualization techniques.