Skip to content

Commit 37dbf4a

Browse files
authored
Merge pull request #256 from java-operator-sdk/tomcat-sample
update Tomcat sample to use EventSources
2 parents 507868b + 036006b commit 37dbf4a

File tree

10 files changed

+271
-133
lines changed

10 files changed

+271
-133
lines changed

samples/tomcat/README.md

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
Creates a Tomcat deployment from a Custom Resource, while keeping the WAR separated with another Custom Resource.
44

5+
This sample demonstrates the following capabilities of the Java Operator SDK:
6+
* Multiple Controllers in a single Operator. The Tomcat resource is managed by the TomcatController while the Webapp
7+
resource is managed by the WebappController.
8+
* Reacting to events about resources created by the controller. The TomcatController will receive events about the
9+
Deployment resources it created. See EventSource section below for more detail.
10+
511
## Example input for creating a Tomcat instance
612
```
713
apiVersion: "tomcatoperator.io/v1"
@@ -27,17 +33,35 @@ spec:
2733

2834
## Getting started / Testing
2935

30-
The quickest way to try the operator is to run it on your local machine, while it connects to a local or remote Kubernetes cluster. When you start it it will use the current kubectl context on your machine to connect to the cluster.
36+
The quickest way to try the operator is to run it on your local machine, while it connects to a local or remote
37+
Kubernetes cluster. When you start it, it will use the current kubectl context on your machine to connect to the cluster.
3138

3239
Before you run it you have to install the CRD on your cluster by running `kubectl apply -f k8s/crd.yaml`.
3340

34-
When the Operator is running you can create some Tomcat Custom Resources. You can find a sample custom resources in the k8s folder.
41+
When the Operator is running you can create some Tomcat Custom Resources. You can find a sample custom resources
42+
in the k8s folder.
3543

3644
If you want the Operator to be running as a deployment in your cluster, follow the below steps.
3745

3846
## Build
39-
You can build the sample using `mvn install jib:dockerBuild` this will produce a Docker image you can push to the registry of your choice. The jar file is built using your local Maven and JDK and then copied into the Docker image.
47+
You can build the sample using `mvn install jib:dockerBuild` this will produce a Docker image you can push to the
48+
registry of your choice. The jar file is built using your local Maven and JDK and then copied into the Docker image.
49+
50+
## Install Operator into cluster
51+
52+
Run `kubectl apply -f k8s/crd.yaml` if you haven't already, then run `kubectl apply -f k8s/operator.yaml`.
53+
Now you can create Tomcat instances with CRs (see examples above).
54+
55+
## EventSources
56+
The TomcatController is listening to events about Deployments created by the TomcatOperator by registering a
57+
DeploymentEventSource with the EventSourceManager. The DeploymentEventSource will in turn register a watch on
58+
all Deployments managed by the Controller (identified by the `managed-by` label).
59+
When an event from a Deployment is received we have to identify which Tomcat object does the Deployment
60+
belong to. This is done when the DeploymentEventSource creates the DeploymentEvent.
4061

41-
## Install Operator into cluster
62+
The TomcatController has to take care of setting the `managed-by` label on the Deployment so the
63+
DeploymentEventSource can watch the right Deployments.
64+
The TomcatController also has to set `ownerReference` on the Deployment so later the DeploymentEventSource can
65+
identify which Tomcat does the Deployment belong to. This is necessary so the frameowork can call the Controller
66+
`createOrUpdate` method correctly.
4267

43-
Run `kubectl apply -f k8s/crd.yaml` if you haven't already, then run `kubectl apply -f k8s/operator.yaml`. Now you can create Tomcat instances with CRs (see examples above).

samples/tomcat/pom.xml

Lines changed: 14 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,11 @@
1212

1313
<artifactId>tomcat-sample</artifactId>
1414
<name>Operator SDK - Samples - Tomcat</name>
15-
<description>Provisions a Tomcat server based on CRDs</description>
15+
<description>Provisions Tomcat Pods and deploys Webapplications in them</description>
1616
<packaging>jar</packaging>
1717

1818
<properties>
1919
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
20-
<java-operator-sdk.version>1.3.0</java-operator-sdk.version>
21-
<java.version>11</java.version>
2220
<maven.compiler.source>11</maven.compiler.source>
2321
<maven.compiler.target>11</maven.compiler.target>
2422
<jib-maven-plugin.version>2.5.2</jib-maven-plugin.version>
@@ -43,68 +41,30 @@
4341
<dependency>
4442
<groupId>commons-io</groupId>
4543
<artifactId>commons-io</artifactId>
46-
<version>2.8.0</version>
47-
</dependency>
48-
<dependency>
49-
<groupId>io.fabric8</groupId>
50-
<artifactId>kubernetes-client</artifactId>
51-
<version>4.12.0</version>
44+
<version>2.6</version>
5245
</dependency>
5346
</dependencies>
5447

5548
<build>
5649
<plugins>
5750
<plugin>
58-
<groupId>org.apache.maven.plugins</groupId>
59-
<artifactId>maven-compiler-plugin</artifactId>
60-
<version>3.8.1</version>
61-
</plugin>
62-
<plugin>
63-
<groupId>com.spotify</groupId>
64-
<artifactId>dockerfile-maven-plugin</artifactId>
65-
<version>1.4.13</version>
51+
<groupId>com.google.cloud.tools</groupId>
52+
<artifactId>jib-maven-plugin</artifactId>
53+
<version>${jib-maven-plugin.version}</version>
6654
<configuration>
67-
<repository>tomcat-operator</repository>
68-
<tag>latest</tag>
69-
<buildArgs>
70-
<JAR_FILE>${project.build.finalName}.jar</JAR_FILE>
71-
</buildArgs>
55+
<from>
56+
<image>gcr.io/distroless/java:11</image>
57+
</from>
58+
<to>
59+
<image>eu.gcr.io/adamsandor-test/tomcat-operator</image>
60+
</to>
7261
</configuration>
7362
</plugin>
7463
<plugin>
7564
<groupId>org.apache.maven.plugins</groupId>
76-
<artifactId>maven-shade-plugin</artifactId>
77-
<version>3.2.4</version>
78-
<executions>
79-
<execution>
80-
<phase>package</phase>
81-
<goals>
82-
<goal>shade</goal>
83-
</goals>
84-
<configuration>
85-
<createDependencyReducedPom>false</createDependencyReducedPom>
86-
<transformers>
87-
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
88-
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
89-
<manifestEntries>
90-
<Main-Class>io.javaoperatorsdk.operator.sample.TomcatOperator</Main-Class>
91-
<Build-Number>1.0</Build-Number>
92-
<Multi-Release>true</Multi-Release>
93-
</manifestEntries>
94-
</transformer>
95-
</transformers>
96-
<filters>
97-
<filter>
98-
<artifact>io.fabric8:openshift-client</artifact>
99-
<excludes>
100-
<exclude>io/fabric8/kubernetes/client/Config*</exclude>
101-
</excludes>
102-
</filter>
103-
</filters>
104-
</configuration>
105-
</execution>
106-
</executions>
65+
<artifactId>maven-compiler-plugin</artifactId>
66+
<version>3.8.1</version>
10767
</plugin>
10868
</plugins>
10969
</build>
110-
</project>
70+
</project>

samples/tomcat/src/main/java/META-INF/MANIFEST.MF

Lines changed: 0 additions & 3 deletions
This file was deleted.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package io.javaoperatorsdk.operator.sample;
2+
3+
import io.fabric8.kubernetes.api.model.apps.Deployment;
4+
import io.fabric8.kubernetes.client.Watcher;
5+
import io.javaoperatorsdk.operator.processing.event.AbstractEvent;
6+
7+
public class DeploymentEvent extends AbstractEvent {
8+
9+
private final Watcher.Action action;
10+
private final Deployment deployment;
11+
12+
public DeploymentEvent(
13+
Watcher.Action action, Deployment resource, DeploymentEventSource deploymentEventSource) {
14+
// TODO: this mapping is really critical and should be made more explicit
15+
super(resource.getMetadata().getOwnerReferences().get(0).getUid(), deploymentEventSource);
16+
this.action = action;
17+
this.deployment = resource;
18+
}
19+
20+
public Watcher.Action getAction() {
21+
return action;
22+
}
23+
24+
public String resourceUid() {
25+
return getDeployment().getMetadata().getUid();
26+
}
27+
28+
@Override
29+
public String toString() {
30+
return "CustomResourceEvent{"
31+
+ "action="
32+
+ action
33+
+ ", resource=[ name="
34+
+ getDeployment().getMetadata().getName()
35+
+ ", kind="
36+
+ getDeployment().getKind()
37+
+ ", apiVersion="
38+
+ getDeployment().getApiVersion()
39+
+ " ,resourceVersion="
40+
+ getDeployment().getMetadata().getResourceVersion()
41+
+ ", markedForDeletion: "
42+
+ (getDeployment().getMetadata().getDeletionTimestamp() != null
43+
&& !getDeployment().getMetadata().getDeletionTimestamp().isEmpty())
44+
+ " ]"
45+
+ '}';
46+
}
47+
48+
public Deployment getDeployment() {
49+
return deployment;
50+
}
51+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package io.javaoperatorsdk.operator.sample;
2+
3+
import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getUID;
4+
import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getVersion;
5+
import static java.net.HttpURLConnection.HTTP_GONE;
6+
7+
import io.fabric8.kubernetes.api.model.apps.Deployment;
8+
import io.fabric8.kubernetes.client.KubernetesClient;
9+
import io.fabric8.kubernetes.client.KubernetesClientException;
10+
import io.fabric8.kubernetes.client.Watcher;
11+
import io.javaoperatorsdk.operator.processing.event.AbstractEventSource;
12+
import org.slf4j.Logger;
13+
import org.slf4j.LoggerFactory;
14+
15+
public class DeploymentEventSource extends AbstractEventSource implements Watcher<Deployment> {
16+
private static final Logger log = LoggerFactory.getLogger(DeploymentEventSource.class);
17+
18+
private final KubernetesClient client;
19+
20+
public static DeploymentEventSource createAndRegisterWatch(KubernetesClient client) {
21+
DeploymentEventSource deploymentEventSource = new DeploymentEventSource(client);
22+
deploymentEventSource.registerWatch();
23+
return deploymentEventSource;
24+
}
25+
26+
private DeploymentEventSource(KubernetesClient client) {
27+
this.client = client;
28+
}
29+
30+
private void registerWatch() {
31+
client
32+
.apps()
33+
.deployments()
34+
.inAnyNamespace()
35+
.withLabel("managed-by", "tomcat-operator")
36+
.watch(this);
37+
}
38+
39+
@Override
40+
public void eventReceived(Action action, Deployment deployment) {
41+
log.info(
42+
"Event received for action: {}, Deployment: {} (rr={})",
43+
action.name(),
44+
deployment.getMetadata().getName(),
45+
deployment.getStatus().getReadyReplicas());
46+
47+
if (action == Action.ERROR) {
48+
log.warn(
49+
"Skipping {} event for custom resource uid: {}, version: {}",
50+
action,
51+
getUID(deployment),
52+
getVersion(deployment));
53+
return;
54+
}
55+
56+
eventHandler.handleEvent(new DeploymentEvent(action, deployment, this));
57+
}
58+
59+
@Override
60+
public void onClose(KubernetesClientException e) {
61+
if (e == null) {
62+
return;
63+
}
64+
if (e.getCode() == HTTP_GONE) {
65+
log.warn("Received error for watch, will try to reconnect.", e);
66+
registerWatch();
67+
} else {
68+
// Note that this should not happen normally, since fabric8 client handles reconnect.
69+
// In case it tries to reconnect this method is not called.
70+
log.error("Unexpected error happened with watch. Will exit.", e);
71+
System.exit(1);
72+
}
73+
}
74+
}

0 commit comments

Comments
 (0)