├── .gitignore ├── LICENSE.md ├── README.adoc ├── configuration └── settings.xml ├── pom.xml ├── sample-configmap.yml ├── sample-secret.yml └── src ├── main ├── java │ └── io │ │ └── fabric8 │ │ └── quickstarts │ │ └── camel │ │ └── config │ │ ├── Application.java │ │ └── QuickstartConfiguration.java ├── jkube │ ├── deployment.yml │ ├── rb.yml │ ├── role.yml │ └── sa.yml └── resources │ ├── application.properties │ ├── bootstrap.yml │ ├── logback.xml │ └── spring │ └── camel-context.xml └── test ├── java └── io │ └── fabric8 │ └── quickstarts │ └── camel │ └── config │ ├── KubernetesIntegrationKT.java │ └── support │ ├── KubernetesTestConfig.java │ ├── KubernetesTestDeployer.java │ ├── KubernetesTestSetup.java │ └── KubernetesTestUtil.java └── resources ├── kubernetesTest.properties └── test-secret.json /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .idea 3 | *.iml 4 | *.im 5 | *.ipr 6 | *.iws 7 | overlays 8 | .DS_Store 9 | .settings 10 | *.swp 11 | *.log 12 | .project 13 | .classpath 14 | *.fmd 15 | .cache 16 | dependency-reduced-pom.xml 17 | kube-cluster/kubernetes 18 | apps/modifiedFabric8.json 19 | git-clones 20 | /bin/ 21 | .vscode/ 22 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Spring-Boot Camel QuickStart using ConfigMaps and Secrets 2 | 3 | This quickstart demonstrates how to configure a Spring-Boot application using Kubernetes ConfigMaps and Secrets. 4 | 5 | A route generates sample messages that are delivered to a list of recipient endpoints 6 | configured through a property named `quickstart.recipients` in the `src/main/resources/application.properties` file. 7 | The property can be overridden using a Kubernetes ConfigMap object. 8 | As soon as a ConfigMap named `camel-config` (containing a property named `application.properties`) is created or changed in the namespace, 9 | an application-context refresh event will be triggered and the logs will reflect the new configuration. 10 | A sample `ConfigMap` (`sample-configmap.yml`) is contained in this repository (it changes the configuration to use all available endpoints in the `recipientList`). 11 | 12 | The quickstart will run on Openshift using a `ServiceAccount` named `qs-camel-config`, with the `view` role granted. 13 | This way, the application is allowed to read the `ConfigMap` and to listen for changes in the current Openshift project. 14 | 15 | Secrets can also be used to configure the application (a sample username/password combination is configured using secrets in this quickstart). 16 | Unlike the `ConfigMap` objects, secrets require higher permissions in order to be read using the Openshift APIs. 17 | To overcome this security limitation, the approach used in this quickstart is to mount the secret as a volume in the Pod and 18 | configure its location in the spring-cloud config file (`src/main/resources/bootstrap.yml`). 19 | 20 | A sample secret (`sample-secret.yml`) is contained in this repository (it just replaces the username `wrong-username` with `myuser`). 21 | 22 | **Note: a secret named `camel-config` must be present in the namespace before the application is deployed** 23 | (otherwise the container remains in a pending status, waiting for it). 24 | 25 | The application utilizes the Spring http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/ImportResource.html[`@ImportResource`] annotation to load a Camel Context definition via a _src/main/resources/spring/camel-context.xml_ file on the classpath. 26 | 27 | IMPORTANT: This quickstart can run in 2 modes: standalone on your machine and on Kubernetes / OpenShift Cluster. Quickstart requires Java 8 or Java 11 (`fuse-java-openshift-jdk11-rhel8` image is used to build in Java 11). 28 | 29 | == Deployment options 30 | 31 | You can run this quickstart in the following modes: 32 | 33 | * Kubernetese / Single-node OpenShift cluster 34 | * Standalone on your machine 35 | 36 | The most effective way to run this quickstart is to deploy and run the project on OpenShift. 37 | 38 | For more details about running this quickstart on a single-node OpenShift cluster, CI/CD deployments, as well as the rest of the runtime, see the link:http://appdev.openshift.io/docs/spring-boot-runtime.html[Spring Boot Runtime Guide]. 39 | 40 | == Running the Quickstart on a single-node Kubernetes/OpenShift cluster 41 | 42 | IMPORTANT: You need to run this example on Container Development Kit 3.3 or OpenShift 3.7. 43 | Both of these products have suitable Fuse images pre-installed. 44 | If you run it in an environment where those images are not preinstalled follow the steps described in <>. 45 | 46 | A single-node Kubernetes/OpenShift cluster provides you with access to a cloud environment that is similar to a production environment. 47 | 48 | If you have a single-node Kubernetes/OpenShift cluster, such as Minishift or the Red Hat Container Development Kit, link:http://appdev.openshift.io/docs/minishift-installation.html[installed and running], you can deploy your quickstart there. 49 | 50 | 51 | . Log in to your OpenShift cluster: 52 | + 53 | [source,bash,options="nowrap",subs="attributes+"] 54 | ---- 55 | $ oc login -u developer -p developer 56 | ---- 57 | 58 | . Create a new OpenShift project for the quickstart: 59 | + 60 | [source,bash,options="nowrap",subs="attributes+"] 61 | ---- 62 | $ oc new-project MY_PROJECT_NAME 63 | ---- 64 | 65 | . Change the directory to the folder that contains the extracted quickstart application (for example, `my_openshift/spring-boot-camel-config`) : 66 | + 67 | [source,bash,options="nowrap",subs="attributes+"] 68 | ---- 69 | $ cd my_openshift/spring-boot-camel-config 70 | ---- 71 | 72 | . Create the (**required**) secret: 73 | + 74 | ---- 75 | $ oc create -f sample-secret.yml 76 | ---- 77 | 78 | . Create the ConfigMap (the ConfigMap can be also created after the application has been deployed, to see the live-reload feature in action): 79 | + 80 | ---- 81 | $ oc create -f sample-configmap.yml 82 | ---- 83 | 84 | . Build and deploy the project to the OpenShift cluster: 85 | + 86 | [source,bash,options="nowrap",subs="attributes+"] 87 | ---- 88 | $ mvn clean -DskipTests oc:deploy -Popenshift 89 | ---- 90 | 91 | . In your browser, navigate to the `MY_PROJECT_NAME` project in the OpenShift console. 92 | Wait until you can see that the pod for the `spring-boot-camel-config` has started up. 93 | 94 | . On the project's `Overview` page, navigate to the details page deployment of the `spring-boot-camel-config` application: `https://OPENSHIFT_IP_ADDR:8443/console/project/MY_PROJECT_NAME/browse/rc/spring-boot-camel-config-NUMBER_OF_DEPLOYMENT?tab=details`. 95 | 96 | . Switch to tab `Logs` and then see the messages sent by Camel. 97 | 98 | [#single-node-without-preinstalled-images] 99 | === Running the Quickstart on a single-node Kubernetes/OpenShift cluster without preinstalled images 100 | 101 | A single-node Kubernetes/OpenShift cluster provides you with access to a cloud environment that is similar to a production environment. 102 | 103 | If you have a single-node Kubernetes/OpenShift cluster, such as Minishift or the Red Hat Container Development Kit, link:http://appdev.openshift.io/docs/minishift-installation.html[installed and running], you can deploy your quickstart there. 104 | 105 | 106 | . Log in to your OpenShift cluster: 107 | + 108 | [source,bash,options="nowrap",subs="attributes+"] 109 | ---- 110 | $ oc login -u developer -p developer 111 | ---- 112 | 113 | . Create a new OpenShift project for the quickstart: 114 | + 115 | [source,bash,options="nowrap",subs="attributes+"] 116 | ---- 117 | $ oc new-project MY_PROJECT_NAME 118 | ---- 119 | 120 | . Configure Red Hat Container Registry authentication (if it is not configured). 121 | Follow https://access.redhat.com/documentation/en-us/red_hat_fuse/7.13/html-single/fuse_on_openshift_guide/index#configure-container-registry[documentation]. 122 | 123 | . Import base images in your newly created project (MY_PROJECT_NAME): 124 | + 125 | [source,bash,options="nowrap",subs="attributes+"] 126 | ---- 127 | $ oc import-image fuse-java-openshift:1.13 --from=registry.redhat.io/fuse7/fuse-java-openshift:1.13 --confirm 128 | ---- 129 | 130 | . Change the directory to the folder that contains the extracted quickstart application (for example, `my_openshift/spring-boot-camel-config`) : 131 | + 132 | [source,bash,options="nowrap",subs="attributes+"] 133 | ---- 134 | $ cd my_openshift/spring-boot-camel-config 135 | ---- 136 | 137 | . Create the (**required**) secret: 138 | + 139 | ---- 140 | $ oc create -f sample-secret.yml 141 | ---- 142 | 143 | . Create the ConfigMap (the ConfigMap can be also created after the application has been deployed, to see the live-reload feature in action): 144 | + 145 | ---- 146 | $ oc create -f sample-configmap.yml 147 | ---- 148 | 149 | . Build and deploy the project to the OpenShift cluster: 150 | + 151 | [source,bash,options="nowrap",subs="attributes+"] 152 | ---- 153 | $ mvn clean -DskipTests oc:deploy -Popenshift -Djkube.generator.fromMode=istag -Djkube.generator.from=MY_PROJECT_NAME/fuse-java-openshift:1.13 154 | ---- 155 | 156 | . In your browser, navigate to the `MY_PROJECT_NAME` project in the OpenShift console. 157 | Wait until you can see that the pod for the `spring-boot-camel-config` has started up. 158 | 159 | . On the project's `Overview` page, navigate to the details page deployment of the `spring-boot-camel-config` application: `https://OPENSHIFT_IP_ADDR:8443/console/project/MY_PROJECT_NAME/browse/rc/spring-boot-camel-config-xml-NUMBER_OF_DEPLOYMENT?tab=details`. 160 | 161 | . Switch to tab `Logs` and then see the messages sent by Camel. 162 | 163 | == Integration Testing 164 | 165 | The example includes a Kubernetes Integration Test. 166 | Once the container image has been built and deployed in Kubernetes, the integration test can be run with: 167 | 168 | [source,bash,options="nowrap",subs="attributes+"] 169 | ---- 170 | mvn test -Dtest=*KT 171 | ---- 172 | 173 | The test is disabled by default and has to be enabled using `-Dtest`. 174 | 175 | == Running the quickstart standalone on your machine 176 | To run this quickstart as a standalone project on your local machine: 177 | 178 | . Download the project and extract the archive on your local filesystem. 179 | . Build the project: 180 | + 181 | [source,bash,options="nowrap",subs="attributes+"] 182 | ---- 183 | $ cd PROJECT_DIR 184 | $ mvn clean package 185 | ---- 186 | . Run the service: 187 | 188 | + 189 | [source,bash,options="nowrap",subs="attributes+"] 190 | ---- 191 | $ mvn spring-boot:run 192 | ---- 193 | . See the messages sent by Camel. 194 | -------------------------------------------------------------------------------- /configuration/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 22 | 23 | 24 | 25 | fusesource.repo 26 | 27 | 28 | maven.central 29 | Maven Central 30 | https://repo1.maven.org/maven2 31 | 32 | false 33 | 34 | 35 | true 36 | never 37 | 38 | 39 | 40 | redhat.ga 41 | Red Hat General Availability Repository 42 | https://maven.repository.redhat.com/ga 43 | 44 | false 45 | 46 | 47 | true 48 | never 49 | 50 | 51 | 52 | redhat.earlyaccess 53 | Red Hat General Early Access Repository 54 | https://maven.repository.redhat.com/earlyaccess 55 | 56 | false 57 | 58 | 59 | true 60 | never 61 | 62 | 63 | 64 | fusesource.m2 65 | FuseSource Community Release Repository 66 | https://repo.fusesource.com/nexus/content/groups/public 67 | 68 | false 69 | 70 | 71 | true 72 | never 73 | 74 | 75 | 76 | fusesource.ea 77 | FuseSource Community Early Access Release Repository 78 | https://repo.fusesource.com/nexus/content/groups/ea 79 | 80 | false 81 | 82 | 83 | true 84 | never 85 | 86 | 87 | 88 | 89 | 90 | maven.central 91 | Maven Central 92 | https://repo1.maven.org/maven2 93 | 94 | false 95 | 96 | 97 | true 98 | never 99 | 100 | 101 | 102 | redhat.ga 103 | Red Hat General Availability Repository 104 | https://maven.repository.redhat.com/ga 105 | 106 | false 107 | 108 | 109 | true 110 | never 111 | 112 | 113 | 114 | redhat.earlyaccess 115 | Red Hat General Early Access Repository 116 | https://maven.repository.redhat.com/earlyaccess 117 | 118 | false 119 | 120 | 121 | true 122 | never 123 | 124 | 125 | 126 | fusesource.m2 127 | FuseSource Community Release Repository 128 | https://repo.fusesource.com/nexus/content/groups/public 129 | 130 | false 131 | 132 | 133 | true 134 | never 135 | 136 | 137 | 138 | fusesource.ea 139 | FuseSource Community Early Access Release Repository 140 | https://repo.fusesource.com/nexus/content/groups/ea 141 | 142 | false 143 | 144 | 145 | true 146 | never 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | fusesource.repo 155 | 156 | 157 | 158 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 21 | 22 | 4.0.0 23 | 24 | io.fabric8.quickstarts 25 | spring-boot-camel-config 26 | 1.0-SNAPSHOT 27 | 28 | 29 | Fabric8 :: Quickstarts :: Spring Boot :: Camel Config 30 | Spring Boot example running a Camel route configured using Kubernetes ConfigMaps and Secrets 31 | 32 | 33 | 34 | UTF-8 35 | UTF-8 36 | 37 | 38 | 7.12.0.fuse-7_12_0-00016-redhat-00001 39 | 1.13 40 | 41 | 42 | 3.7.0 43 | 2.22.2 44 | 45 | 46 | 47 | 48 | 49 | org.jboss.redhat-fuse 50 | fuse-springboot-bom 51 | ${fuse.bom.version} 52 | pom 53 | import 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-actuator 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-starter-web 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-starter-tomcat 72 | 73 | 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-starter-undertow 78 | 79 | 80 | 81 | 82 | org.apache.camel 83 | camel-spring-boot-starter 84 | 85 | 86 | 87 | 88 | org.springframework.cloud 89 | spring-cloud-starter-kubernetes-client-config 90 | 91 | 92 | 93 | io.fabric8 94 | kubernetes-client 95 | 96 | 97 | 98 | io.fabric8 99 | kubernetes-model 100 | 101 | 102 | 103 | 104 | junit 105 | junit 106 | test 107 | 108 | 109 | 110 | io.fabric8 111 | openshift-client 112 | 4.6.2 113 | test 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | src/test/resources 122 | true 123 | 124 | 125 | 126 | 127 | 128 | 129 | org.apache.maven.plugins 130 | maven-compiler-plugin 131 | ${maven-compiler-plugin.version} 132 | 133 | 1.8 134 | 1.8 135 | 136 | 137 | 138 | org.apache.maven.plugins 139 | maven-surefire-plugin 140 | ${maven-surefire-plugin.version} 141 | true 142 | 143 | 15 144 | -DenableImageStreamDetection=true 145 | 146 | **/*KT.java 147 | 148 | 149 | 150 | 151 | 152 | org.jboss.redhat-fuse 153 | spring-boot-maven-plugin 154 | ${fuse.bom.version} 155 | 156 | 157 | 158 | repackage 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | openshift 170 | 171 | registry.redhat.io/fuse7/fuse-java-openshift-rhel8:${docker.image.version} 172 | 173 | 174 | 175 | 176 | org.jboss.redhat-fuse 177 | openshift-maven-plugin 178 | ${fuse.bom.version} 179 | 180 | 181 | 182 | resource 183 | build 184 | apply 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | com.company 194 | Red_Hat 195 | 196 | 197 | rht.prod_name 198 | Red_Hat_Integration 199 | 200 | 201 | rht.prod_ver 202 | 7.13.0 203 | 204 | 205 | rht.comp 206 | spring-boot-camel-config 207 | 208 | 209 | rht.comp_ver 210 | ${fuse.bom.version} 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | java11 222 | 223 | registry.redhat.io/fuse7/fuse-java-openshift-jdk11-rhel8:${docker.image.version} 224 | 225 | 226 | [11,17) 227 | 228 | 229 | 230 | java17 231 | 232 | registry.redhat.io/fuse7/fuse-java-openshift-jdk17-rhel8:${docker.image.version} 233 | 234 | 235 | [17,) 236 | 237 | 238 | 239 | 240 | 241 | 242 | redhat-ga-repository 243 | https://maven.repository.redhat.com/ga 244 | 245 | true 246 | 247 | 248 | false 249 | 250 | 251 | 252 | redhat-ea-repository 253 | https://maven.repository.redhat.com/earlyaccess/all 254 | 255 | true 256 | 257 | 258 | false 259 | 260 | 261 | 262 | 263 | 264 | 265 | redhat-ga-repository 266 | https://maven.repository.redhat.com/ga 267 | 268 | true 269 | 270 | 271 | false 272 | 273 | 274 | 275 | redhat-ea-repository 276 | https://maven.repository.redhat.com/earlyaccess/all 277 | 278 | true 279 | 280 | 281 | false 282 | 283 | 284 | 285 | 286 | -------------------------------------------------------------------------------- /sample-configmap.yml: -------------------------------------------------------------------------------- 1 | kind: ConfigMap 2 | apiVersion: v1 3 | metadata: 4 | # Must match the 'spring.application.name' property of the application 5 | name: camel-config 6 | data: 7 | application.properties: | 8 | # Override the configuration properties here 9 | quickstart.recipients=direct:async-queue,direct:file,direct:mail -------------------------------------------------------------------------------- /sample-secret.yml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: camel-config 5 | type: Opaque 6 | data: 7 | # The username is 'myuser' 8 | quickstart.queue-username: bXl1c2VyCg== 9 | quickstart.queue-password: MWYyZDFlMmU2N2Rm -------------------------------------------------------------------------------- /src/main/java/io/fabric8/quickstarts/camel/config/Application.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2005-2016 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 5 | * 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13 | * implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | package io.fabric8.quickstarts.camel.config; 17 | 18 | import org.springframework.boot.SpringApplication; 19 | import org.springframework.boot.autoconfigure.SpringBootApplication; 20 | import org.springframework.context.annotation.ImportResource; 21 | 22 | /** 23 | * The Spring-boot main class. 24 | */ 25 | @SpringBootApplication 26 | @ImportResource({"classpath:spring/camel-context.xml"}) 27 | public class Application { 28 | 29 | public static void main(String[] args) { 30 | SpringApplication.run(Application.class, args); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/io/fabric8/quickstarts/camel/config/QuickstartConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2005-2016 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 5 | * 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13 | * implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | package io.fabric8.quickstarts.camel.config; 17 | 18 | import org.springframework.boot.context.properties.ConfigurationProperties; 19 | import org.springframework.context.annotation.Configuration; 20 | 21 | @Configuration 22 | @ConfigurationProperties(prefix = "quickstart") 23 | public class QuickstartConfiguration { 24 | 25 | /** 26 | * A comma-separated list of routes to use as recipients for messages. 27 | */ 28 | private String recipients; 29 | 30 | /** 31 | * The username to use when connecting to the async queue (simulation) 32 | */ 33 | private String queueUsername; 34 | 35 | /** 36 | * The password to use when connecting to the async queue (simulation) 37 | */ 38 | private String queuePassword; 39 | 40 | public String getRecipients() { 41 | return recipients; 42 | } 43 | 44 | public void setRecipients(String recipients) { 45 | this.recipients = recipients; 46 | } 47 | 48 | public String getQueueUsername() { 49 | return queueUsername; 50 | } 51 | 52 | public void setQueueUsername(String queueUsername) { 53 | this.queueUsername = queueUsername; 54 | } 55 | 56 | public String getQueuePassword() { 57 | return queuePassword; 58 | } 59 | 60 | public void setQueuePassword(String queuePassword) { 61 | this.queuePassword = queuePassword; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/jkube/deployment.yml: -------------------------------------------------------------------------------- 1 | spec: 2 | template: 3 | spec: 4 | serviceAccountName: "qs-camel-config" 5 | volumes: 6 | - name: "camel-config" 7 | secret: 8 | # The secret must be created before deploying this application 9 | secretName: "camel-config" 10 | containers: 11 | - 12 | volumeMounts: 13 | - name: "camel-config" 14 | readOnly: true 15 | # Mount the secret where spring-cloud-kubernetes is configured to read it 16 | # see src/main/resources/bootstrap.yml 17 | mountPath: "/etc/secrets/camel-config" 18 | resources: 19 | requests: 20 | cpu: "0.2" 21 | memory: 256Mi 22 | limits: 23 | cpu: "1.0" 24 | memory: 256Mi 25 | env: 26 | - name: SPRING_APPLICATION_JSON 27 | value: '{"server":{"undertow":{"io-threads":1, "worker-threads":2 }}}' 28 | -------------------------------------------------------------------------------- /src/main/jkube/rb.yml: -------------------------------------------------------------------------------- 1 | kind: "RoleBinding" 2 | apiVersion: "rbac.authorization.k8s.io/v1" 3 | metadata: 4 | name: "qs-camel-config" 5 | roleRef: 6 | # Add the "namespace-reader" role to the service account 7 | kind: "Role" 8 | name: "namespace-reader" 9 | subjects: 10 | - kind: "ServiceAccount" 11 | name: "qs-camel-config" 12 | -------------------------------------------------------------------------------- /src/main/jkube/role.yml: -------------------------------------------------------------------------------- 1 | kind: "Role" 2 | apiVersion: "rbac.authorization.k8s.io/v1" 3 | metadata: 4 | name: "namespace-reader" 5 | rules: 6 | - apiGroups: ["", "extensions", "apps"] 7 | resources: ["configmaps", "pods", "services", "endpoints", "secrets"] 8 | verbs: ["get", "list", "watch"] -------------------------------------------------------------------------------- /src/main/jkube/sa.yml: -------------------------------------------------------------------------------- 1 | apiVersion: "v1" 2 | kind: "ServiceAccount" 3 | metadata: 4 | name: "qs-camel-config" 5 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # Binding health checks to an internal port 2 | management.server.port=8081 3 | 4 | management.endpoints.web.exposure.include=health,info,restart 5 | 6 | # disable all management enpoints except health 7 | management.endpoints.enabled-by-default=false 8 | management.endpoint.health.enabled=true 9 | 10 | 11 | logging.config=classpath:logback.xml 12 | 13 | # The name of the Camel app 14 | camel.springboot.name=CamelConfig 15 | 16 | # Keeps the application alive 17 | camel.springboot.main-run-controller=true 18 | 19 | # Default quickstart configuration (overridden at runtime using ConfigMaps and Secrets) 20 | quickstart.recipients=direct:async-queue,direct:file 21 | 22 | quickstart.queue-username=wrong-username 23 | quickstart.queue-password=wrong-password 24 | -------------------------------------------------------------------------------- /src/main/resources/bootstrap.yml: -------------------------------------------------------------------------------- 1 | # Startup configuration of Spring-cloud-kubernetes 2 | spring: 3 | application: 4 | name: camel-config 5 | cloud: 6 | kubernetes: 7 | reload: 8 | # Enable live reload on ConfigMap change (disabled for Secrets by default) 9 | enabled: true 10 | secrets: 11 | paths: /etc/secrets/camel-config 12 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/spring/camel-context.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | message-${header.CamelTimerCounter} 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /src/test/java/io/fabric8/quickstarts/camel/config/KubernetesIntegrationKT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2005-2016 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 5 | * 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 13 | * implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | 17 | package io.fabric8.quickstarts.camel.config; 18 | 19 | import io.fabric8.kubernetes.api.model.Pod; 20 | import io.fabric8.kubernetes.api.model.PodList; 21 | import io.fabric8.kubernetes.client.KubernetesClient; 22 | import io.fabric8.quickstarts.camel.config.support.KubernetesTestConfig; 23 | import io.fabric8.quickstarts.camel.config.support.KubernetesTestSetup; 24 | import org.junit.Assert; 25 | import org.junit.Test; 26 | import org.slf4j.Logger; 27 | import org.slf4j.LoggerFactory; 28 | 29 | import java.util.concurrent.TimeUnit; 30 | 31 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestConfig.createConfig; 32 | 33 | public class KubernetesIntegrationKT { 34 | 35 | private static Logger LOG = LoggerFactory.getLogger(KubernetesIntegrationKT.class); 36 | 37 | 38 | @Test 39 | public void testAppProvisionsRunningPods() { 40 | KubernetesTestConfig config = createConfig(); 41 | KubernetesTestSetup testSetup = new KubernetesTestSetup(config); 42 | 43 | try { 44 | testSetup.setUp(); 45 | KubernetesClient client = config.getClient(); 46 | PodList podList = client.pods().inNamespace(config.getNamespace()).list(); 47 | 48 | if (podList.getItems().isEmpty()) { 49 | Assert.fail("No pods found in namespace "+ config.getNamespace()); 50 | } 51 | 52 | for (Pod pod : podList.getItems()) { 53 | try { 54 | if (!pod.getMetadata().getName().endsWith("build") && !pod.getMetadata().getName().endsWith("deploy")) { 55 | client.resource(pod) 56 | .inNamespace(config.getNamespace()) 57 | .waitUntilReady(config.getKubernetesTimeout(), TimeUnit.SECONDS); 58 | LOG.info("Pod {} is in state: {}",pod.getMetadata().getName(),pod.getStatus().getPhase()); 59 | } 60 | } catch (InterruptedException e) { 61 | Assert.fail("Timeout reached waiting for pod " + pod.getMetadata().getName()); 62 | } 63 | } 64 | } finally { 65 | testSetup.tearDown(); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/io/fabric8/quickstarts/camel/config/support/KubernetesTestConfig.java: -------------------------------------------------------------------------------- 1 | package io.fabric8.quickstarts.camel.config.support; 2 | 3 | import io.fabric8.kubernetes.client.Config; 4 | import io.fabric8.kubernetes.client.ConfigBuilder; 5 | import io.fabric8.kubernetes.client.DefaultKubernetesClient; 6 | import io.fabric8.kubernetes.client.KubernetesClient; 7 | import org.xml.sax.SAXException; 8 | 9 | import javax.xml.parsers.ParserConfigurationException; 10 | import javax.xml.xpath.XPathExpressionException; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.nio.file.Files; 14 | import java.nio.file.Paths; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.Optional; 19 | import java.util.Properties; 20 | import java.util.UUID; 21 | import java.util.function.Predicate; 22 | import java.util.regex.Pattern; 23 | import java.util.stream.Collectors; 24 | import java.util.stream.Stream; 25 | 26 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.failNotDeployed; 27 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.getArrayListStringProperty; 28 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.getArtifactId; 29 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.getBooleanProperty; 30 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.getIntProperty; 31 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.getResourceFileAsStream; 32 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.getStringProperty; 33 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.isNullOrEmpty; 34 | import static java.util.Collections.singletonMap; 35 | import static java.util.Objects.nonNull; 36 | 37 | 38 | public class KubernetesTestConfig { 39 | 40 | 41 | public static final String NAMESPACE_USE_CURRENT = "kt.namespace.use.current"; 42 | public static final String NAMESPACE_TO_USE = "kt.namespace.use.existing"; 43 | public static final String NAMESPACE_DESTROY_ENABLED = "kt.namespace.destroy.enabled"; 44 | public static final String NAMESPACE_PREFIX = "kt.namespace.prefix"; 45 | public static final String RESOUCE_FILE_PATH = "kt.resource.file.path"; 46 | public static final String KUBERNETES_MASTER = "kubernetes.master"; 47 | public static final String KUBERNETES_USERNAME = "kubernetes.username"; 48 | public static final String KUBERNETES_PASSWORD = "kubernetes.password"; 49 | public static final String KUBERNETES_TIMEOUT = "kubernetes.timeout"; 50 | 51 | public static final int DEFAULT_KUBERNETES_TIMEOUT = 300; 52 | public static final String ENV_DEPENDENCIES = "kt.env.dependencies"; 53 | public static final String DEFAULT_NAMESPACE_PREFIX = "ktest"; 54 | 55 | public static final String TARGET_DIR_PATH = System.getProperty("basedir", ".") + "/target"; 56 | public static final String DEFAULT_RESOUCE_FILE_PATH = TARGET_DIR_PATH + "/classes/META-INF/jkube/openshift.yml"; 57 | 58 | public static final String TEST_PROPERTIES_FILE = "kubernetesTest.properties"; 59 | 60 | 61 | private final Properties systemPropertiesVars = System.getProperties(); 62 | 63 | private boolean shouldDestroyNamespace = false; 64 | 65 | private boolean useExistingNamespace = true; 66 | 67 | private String namespace; 68 | 69 | private String resourceFilePath; 70 | 71 | private String imageStreamFilePath; 72 | 73 | private List dependencies; 74 | 75 | private String kubernetesMaster; 76 | 77 | private String kubernetesUsername; 78 | 79 | private String kubernetesPassword; 80 | 81 | private KubernetesClient kubeClient; 82 | 83 | private int kubernetesTimeout; 84 | 85 | private String mainNamespace; 86 | 87 | private Map ktestLabels = singletonMap("scope","ktest"); 88 | 89 | private KubernetesTestConfig() { 90 | } 91 | 92 | public static KubernetesTestConfig createConfig() { 93 | KubernetesTestConfig config = new KubernetesTestConfig(); 94 | config.loadConfiguration(); 95 | return config; 96 | } 97 | 98 | public KubernetesClient getClient() { 99 | if (kubeClient == null) { 100 | if (isNullOrEmpty(kubernetesMaster)) { 101 | kubeClient = new DefaultKubernetesClient(); 102 | }else { 103 | Config config = new ConfigBuilder() 104 | .withMasterUrl(kubernetesMaster) 105 | .withUsername(kubernetesUsername) 106 | .withPassword(kubernetesPassword) 107 | .build(); 108 | kubeClient = new DefaultKubernetesClient(config); 109 | } 110 | } 111 | return kubeClient; 112 | } 113 | 114 | private void loadConfiguration() { 115 | 116 | Properties prop = new Properties(); 117 | 118 | try (InputStream input = getResourceFileAsStream(TEST_PROPERTIES_FILE)) { 119 | // load a properties file 120 | if(nonNull(input)) { 121 | prop.load(input); 122 | } 123 | } catch (IOException e) { 124 | throw new RuntimeException(e); 125 | } 126 | 127 | prop.putAll(systemPropertiesVars); 128 | 129 | Map testConfig = prop.entrySet().stream().collect( 130 | Collectors.toMap( 131 | e -> String.valueOf(e.getKey()), 132 | e -> String.valueOf(e.getValue()), 133 | (prev, next) -> next, 134 | HashMap::new) 135 | ); 136 | String artifactId = null; 137 | try{ 138 | artifactId = getArtifactId(); 139 | } catch (XPathExpressionException | ParserConfigurationException |IOException| SAXException e) { 140 | failNotDeployed(); 141 | } 142 | 143 | namespace = generateNamespaceName(testConfig); 144 | 145 | resourceFilePath = getStringProperty(RESOUCE_FILE_PATH, testConfig, DEFAULT_RESOUCE_FILE_PATH); 146 | 147 | imageStreamFilePath = TARGET_DIR_PATH + "/" + artifactId + "-is.yml" ; 148 | 149 | dependencies = getArrayListStringProperty(ENV_DEPENDENCIES, testConfig); 150 | 151 | kubernetesMaster = getStringProperty(KUBERNETES_MASTER, testConfig, null); 152 | 153 | kubernetesUsername = getStringProperty(KUBERNETES_USERNAME, testConfig, null); 154 | 155 | kubernetesPassword = getStringProperty(KUBERNETES_PASSWORD, testConfig, null); 156 | 157 | kubernetesTimeout = getIntProperty(KUBERNETES_TIMEOUT,testConfig,DEFAULT_KUBERNETES_TIMEOUT); 158 | 159 | shouldDestroyNamespace = getBooleanProperty(NAMESPACE_DESTROY_ENABLED, testConfig, true); 160 | 161 | mainNamespace = extractMainNamespaceName(imageStreamFilePath); 162 | } 163 | 164 | 165 | private String generateNamespaceName(Map config) { 166 | String sessionId = UUID.randomUUID().toString().split("-")[0]; 167 | String namespace = getBooleanProperty(NAMESPACE_USE_CURRENT, config, false) 168 | ? new ConfigBuilder().build().getNamespace() 169 | : getStringProperty(NAMESPACE_TO_USE, config, null); 170 | if (isNullOrEmpty(namespace)) { 171 | namespace = getStringProperty(NAMESPACE_PREFIX, config, DEFAULT_NAMESPACE_PREFIX) + "-" + sessionId; 172 | shouldDestroyNamespace = true; 173 | useExistingNamespace = false; 174 | } 175 | return namespace; 176 | } 177 | 178 | private String extractMainNamespaceName(String imageStreamFilePath){ 179 | Pattern pattern = Pattern.compile("\\s*\"namespace\"\\s*:\\s*\"[a-z0-9]([-a-z0-9]*[a-z0-9])?\".*"); 180 | Predicate namespacePredicate = pattern.asPredicate(); 181 | 182 | Optional mainNamespace = Optional.empty(); 183 | 184 | try (Stream stream = Files.lines(Paths.get(imageStreamFilePath))) { 185 | mainNamespace = stream 186 | .filter(namespacePredicate) 187 | .map(x->pattern.matcher(x).group(1)).findFirst(); 188 | }catch (IOException e) { 189 | failNotDeployed(); 190 | } 191 | return mainNamespace.orElseGet(() -> new DefaultKubernetesClient().getNamespace()); 192 | } 193 | 194 | 195 | // Getter 196 | 197 | 198 | public String getNamespace() { 199 | return namespace; 200 | } 201 | 202 | public String getResourceFilePath() { 203 | return resourceFilePath; 204 | } 205 | 206 | public List getDependencies() { 207 | return dependencies; 208 | } 209 | 210 | public boolean isUseExistingNamespace() { 211 | return useExistingNamespace; 212 | } 213 | 214 | public boolean isShouldDestroyNamespace() { 215 | return shouldDestroyNamespace; 216 | } 217 | 218 | public int getKubernetesTimeout() { 219 | return kubernetesTimeout; 220 | } 221 | 222 | public Map getKtestLabels() { 223 | return ktestLabels; 224 | } 225 | 226 | public String getImageStreamFilePath() { 227 | return imageStreamFilePath; 228 | } 229 | 230 | public String getMainNamespace() { 231 | return mainNamespace; 232 | } 233 | } -------------------------------------------------------------------------------- /src/test/java/io/fabric8/quickstarts/camel/config/support/KubernetesTestDeployer.java: -------------------------------------------------------------------------------- 1 | package io.fabric8.quickstarts.camel.config.support; 2 | 3 | import io.fabric8.kubernetes.api.model.HasMetadata; 4 | import io.fabric8.kubernetes.api.model.Namespace; 5 | import io.fabric8.kubernetes.api.model.NamespaceBuilder; 6 | import io.fabric8.kubernetes.api.model.rbac.RoleBinding; 7 | import io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder; 8 | import io.fabric8.kubernetes.api.model.rbac.Subject; 9 | import io.fabric8.kubernetes.api.model.rbac.SubjectBuilder; 10 | import io.fabric8.kubernetes.client.KubernetesClient; 11 | import io.fabric8.kubernetes.client.KubernetesClientException; 12 | import io.fabric8.kubernetes.client.Watch; 13 | import io.fabric8.kubernetes.client.Watcher; 14 | import io.fabric8.openshift.api.model.ImageLookupPolicy; 15 | import io.fabric8.openshift.api.model.ImageStream; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | 19 | import java.io.FileInputStream; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.util.Arrays; 23 | import java.util.List; 24 | import java.util.concurrent.CountDownLatch; 25 | import java.util.concurrent.TimeUnit; 26 | import java.util.function.Predicate; 27 | import java.util.stream.Collectors; 28 | 29 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.failNotDeployed; 30 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.isNotNullOrEmpty; 31 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestUtil.isNullOrEmpty; 32 | import static java.util.concurrent.TimeUnit.SECONDS; 33 | 34 | public class KubernetesTestDeployer { 35 | 36 | private final static Logger LOG = LoggerFactory.getLogger(KubernetesTestDeployer.class); 37 | 38 | private final static Predicate supportReadiness = 39 | resource -> Arrays.asList("Node", "Deployment", "ReplicaSet", "StatefulSet", "Pod", "DeploymentConfig", "ReplicationController") 40 | .contains(resource.getKind()); 41 | 42 | public static void deploy(KubernetesClient client, KubernetesTestConfig config) { 43 | createNamespace(client, config); 44 | 45 | // deploy dependencies 46 | if (isNotNullOrEmpty(config.getDependencies())) { 47 | LOG.info("Deploy dependencies from file {}", config.getImageStreamFilePath()); 48 | for (String dependency : config.getDependencies()) { 49 | deployFromFile(client, config, dependency); 50 | } 51 | } 52 | 53 | String sourceNamespace = config.getMainNamespace(); 54 | LOG.info("Deploy RoleBinding "); 55 | createRoleBinding(client, sourceNamespace, config); 56 | LOG.info("Deploy ImageStreams from file {}", config.getImageStreamFilePath()); 57 | createImageStream(client, config); 58 | // deploy resources 59 | LOG.info("Deploy resources from file {}", config.getResourceFilePath()); 60 | deployFromFile(client, config, config.getResourceFilePath()); 61 | } 62 | 63 | 64 | private static void deployFromFile(KubernetesClient client, KubernetesTestConfig config, String resourcesFilePath) { 65 | if (isNullOrEmpty(resourcesFilePath)) { 66 | failNotDeployed(); 67 | } 68 | LOG.info("Loading resources file: " + resourcesFilePath); 69 | List resourceList = null; 70 | 71 | try (InputStream resources = new FileInputStream(resourcesFilePath)) { 72 | resourceList = client.load(resources).get(); 73 | } catch (IOException e) { 74 | LOG.error("Problem loading resources file {}", resourcesFilePath); 75 | failNotDeployed(); 76 | } 77 | 78 | List deployedResourceList = client.resourceList(resourceList) 79 | .inNamespace(config.getNamespace()) 80 | .createOrReplace(); 81 | 82 | LOG.info("Waiting for reources to be ready"); 83 | deployedResourceList.stream() 84 | .filter(supportReadiness) 85 | .forEach(resource -> { 86 | try { 87 | client.resource(resource) 88 | .inNamespace(config.getNamespace()) 89 | .waitUntilReady(config.getKubernetesTimeout(), SECONDS); 90 | } catch (InterruptedException e) { 91 | LOG.error("Timeout reached waiting for "+resource.getKind()+" with name "+resource.getMetadata().getName()+" to be ready"); 92 | failNotDeployed(); 93 | } 94 | }); 95 | LOG.info("Reources are ready Now"); 96 | } 97 | 98 | private static void createRoleBinding(KubernetesClient client, String sourceNamespace, KubernetesTestConfig config) { 99 | 100 | String targetNamespace = config.getNamespace(); 101 | 102 | Subject subject = new SubjectBuilder() 103 | .withName("default") 104 | .withKind("ServiceAccount") 105 | .withNamespace(targetNamespace) 106 | .build(); 107 | 108 | RoleBindingBuilder roleBindingBuilder = new RoleBindingBuilder(); 109 | RoleBinding roleBinding = roleBindingBuilder 110 | .withKind("RoleBinding") 111 | .withApiVersion("rbac.authorization.k8s.io/v1") 112 | .withNewMetadata() 113 | .withName("ktest-system:image-puller") 114 | .withNamespace(sourceNamespace) 115 | .withLabels(config.getKtestLabels()) 116 | .endMetadata() 117 | .withSubjects(subject) 118 | .withNewRoleRef() 119 | .withApiGroup("rbac.authorization.k8s.io") 120 | .withKind("ClusterRole") 121 | .withName("system:image-puller") 122 | .endRoleRef() 123 | .build(); 124 | 125 | client.rbac().roleBindings().inNamespace(sourceNamespace).createOrReplace(roleBinding); 126 | } 127 | 128 | private static void createNamespace(KubernetesClient client, KubernetesTestConfig config) { 129 | if (config.isUseExistingNamespace()) { 130 | return; 131 | } 132 | Namespace ns = new NamespaceBuilder().withNewMetadata().withName(config.getNamespace()).endMetadata().build(); 133 | client.namespaces().create(ns); 134 | LOG.info("Namespace " + config.getNamespace() + " created."); 135 | } 136 | 137 | 138 | public static void deleteNamespace(KubernetesClient 139 | client, KubernetesTestConfig config) { 140 | final CountDownLatch isWatchClosed = new CountDownLatch(1); 141 | Watch watch = client.namespaces().withName(config.getNamespace()).watch(new Watcher() { 142 | @Override 143 | public void eventReceived(Action action, Namespace resource) { 144 | if (action.equals(Action.DELETED)) { 145 | LOG.debug("Deleted event for namespace {} received", config.getNamespace()); 146 | isWatchClosed.countDown(); 147 | } 148 | } 149 | @Override 150 | public void onClose(KubernetesClientException cause) { 151 | isWatchClosed.countDown(); 152 | } 153 | }); 154 | try { 155 | if (config.isShouldDestroyNamespace()) { 156 | client.namespaces().withName(config.getNamespace()).delete(); 157 | LOG.info("Waiting for namespace deletion " + config.getNamespace() + " ..."); 158 | isWatchClosed.await(config.getKubernetesTimeout(), TimeUnit.SECONDS); 159 | LOG.info("Namespace - " + config.getNamespace() + " deleted."); 160 | } 161 | } catch (InterruptedException e) { 162 | isWatchClosed.countDown(); 163 | watch.close(); 164 | throw new RuntimeException("Timeout reached while waiting for namespace deletion."); 165 | } 166 | } 167 | 168 | private static void createImageStream(KubernetesClient client, KubernetesTestConfig config) { 169 | try (InputStream imageStreamFile = new FileInputStream(config.getImageStreamFilePath())) { 170 | List result = client.load(imageStreamFile).get(); 171 | result = result.stream().peek( 172 | x -> { 173 | if (x instanceof ImageStream) { 174 | ((ImageStream) x).getSpec() 175 | .setLookupPolicy(new ImageLookupPolicy(true)); 176 | } 177 | } 178 | ).collect(Collectors.toList()); 179 | 180 | client.resourceList(result) 181 | .inNamespace(config.getNamespace()) 182 | .createOrReplace(); 183 | } catch (IOException e) { 184 | failNotDeployed(); 185 | } 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/test/java/io/fabric8/quickstarts/camel/config/support/KubernetesTestSetup.java: -------------------------------------------------------------------------------- 1 | package io.fabric8.quickstarts.camel.config.support; 2 | 3 | import io.fabric8.kubernetes.client.KubernetesClient; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestDeployer.deleteNamespace; 8 | import static io.fabric8.quickstarts.camel.config.support.KubernetesTestDeployer.deploy; 9 | 10 | 11 | public class KubernetesTestSetup { 12 | 13 | protected static Logger LOG = LoggerFactory.getLogger(KubernetesTestSetup.class); 14 | 15 | private KubernetesTestConfig config; 16 | 17 | private KubernetesClient client; 18 | 19 | public KubernetesTestSetup(KubernetesTestConfig config) { 20 | this.config = config; 21 | this.client = config.getClient(); 22 | } 23 | 24 | public void setUp() { 25 | LOG.info("Doing setup..."); 26 | deploy(client, config); 27 | LOG.info("setup done."); 28 | } 29 | 30 | public void tearDown() { 31 | LOG.info("Doing teardown..."); 32 | if(config.isShouldDestroyNamespace()) { 33 | deleteNamespace(client, config); 34 | client.rbac() 35 | .roleBindings() 36 | .inNamespace(config.getMainNamespace()) 37 | .withLabels(config.getKtestLabels()) 38 | .delete(); 39 | }else{ 40 | LOG.info("Nothing to do!"); 41 | } 42 | LOG.info("Teardown done."); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/io/fabric8/quickstarts/camel/config/support/KubernetesTestUtil.java: -------------------------------------------------------------------------------- 1 | package io.fabric8.quickstarts.camel.config.support; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.w3c.dom.Document; 6 | import org.w3c.dom.Node; 7 | import org.xml.sax.SAXException; 8 | 9 | import javax.xml.parsers.DocumentBuilder; 10 | import javax.xml.parsers.DocumentBuilderFactory; 11 | import javax.xml.parsers.ParserConfigurationException; 12 | import javax.xml.xpath.XPath; 13 | import javax.xml.xpath.XPathConstants; 14 | import javax.xml.xpath.XPathExpression; 15 | import javax.xml.xpath.XPathExpressionException; 16 | import javax.xml.xpath.XPathFactory; 17 | import java.io.File; 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | import java.util.Arrays; 21 | import java.util.Collection; 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | public class KubernetesTestUtil { 26 | 27 | protected static Logger LOG = LoggerFactory.getLogger(KubernetesTestUtil.class); 28 | 29 | 30 | public static boolean isNullOrEmpty(String s) { 31 | return s == null || s.isEmpty(); 32 | } 33 | 34 | public static boolean isNullOrEmpty(Collection s) { 35 | return s == null || s.isEmpty(); 36 | } 37 | 38 | 39 | public static boolean isNullOrEmpty(Object [] s) { 40 | return s == null || s.length == 0; 41 | } 42 | 43 | public static boolean isNotNullOrEmpty(String s) { 44 | return !isNullOrEmpty(s); 45 | } 46 | 47 | public static boolean isNotNullOrEmpty(Collection s) { 48 | return !isNullOrEmpty(s); 49 | } 50 | 51 | public static InputStream getResourceFileAsStream(String fileName) { 52 | return KubernetesTestUtil.class.getClassLoader().getResourceAsStream(fileName); 53 | } 54 | 55 | public static void failNotDeployed(){ 56 | String errorMessage = "Error loading resource file. Be sure to run `mvn oc:deploy` before running this integration test."; 57 | LOG.error(errorMessage); 58 | throw new RuntimeException(errorMessage); 59 | } 60 | 61 | public static String getStringProperty(String name, Map map) { 62 | return getStringProperty(name, map, null); 63 | } 64 | public static String getStringProperty(String name, Map map, String defaultValue) { 65 | if (map.containsKey(name) && isNotNullOrEmpty(map.get(name))) { 66 | defaultValue = map.get(name); 67 | } 68 | return defaultValue; 69 | } 70 | 71 | public static List getArrayListStringProperty(String name, Map map) { 72 | if (map.containsKey(name) && isNotNullOrEmpty(map.get(name))) { 73 | return Arrays.asList(map.get(name).split(",")); 74 | } 75 | return null; 76 | } 77 | 78 | public static int getIntProperty(String name, Map map, int defaultValue) { 79 | if (map.containsKey(name) && isNotNullOrEmpty(map.get(name))) { 80 | return Integer.parseInt(map.get(name)); 81 | } 82 | return defaultValue; 83 | } 84 | 85 | public static Boolean getBooleanProperty(String name, Map map, Boolean defaultValue) { 86 | if (map.containsKey(name) && isNotNullOrEmpty(map.get(name))) { 87 | defaultValue = Boolean.parseBoolean(map.get(name)); 88 | } 89 | return defaultValue; 90 | } 91 | 92 | public static String getArtifactId() throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { 93 | 94 | DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 95 | domFactory.setNamespaceAware(true); 96 | 97 | DocumentBuilder builder = domFactory.newDocumentBuilder(); 98 | Document doc = builder.parse(new File("./pom.xml")); 99 | XPath xpath = XPathFactory.newInstance().newXPath(); 100 | 101 | XPathExpression expr = xpath.compile("/*[local-name() = 'project']/*[local-name() = 'artifactId']/text()"); 102 | Node result = (Node) expr.evaluate(doc, XPathConstants.NODE); 103 | String artifactId = result.getTextContent(); 104 | LOG.info("Detected artifactId: {}", artifactId); 105 | return artifactId; 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/test/resources/kubernetesTest.properties: -------------------------------------------------------------------------------- 1 | #### 2 | 3 | ### Use current namespace instead creating a new one. Default false 4 | #kt.namespace.use.current 5 | 6 | ### Use the namespace specified in this property instead creating a new one. 7 | #kt.namespace.use.existing 8 | 9 | ### Delete the namespace at the end of the test. Default true 10 | #kt.namespace.destroy.enabled 11 | 12 | ### Use the namespace prefix specified in this property in this property 13 | ### instead the default one "ktest" 14 | #kt.namespace.prefix 15 | 16 | ### Install the resources loaded from the specified file path. 17 | ### Default: target/classes/META-INF/jkube/openshift.yml 18 | #kt.resource.file.path 19 | 20 | ### The master URI used to login to Kubernetes/Openshift cluster. Autodetected if empty. 21 | #kubernetes.master 22 | 23 | ### The username used to login to Kubernetes/Openshift cluster. Autodetected if empty 24 | #kubernetes.username 25 | 26 | ### The password used to login to Kubernetes/Openshift cluster. Autodetected if empty 27 | #kubernetes.password 28 | 29 | ### How much second the client wait until the newly created resource is ready. Default 60 30 | #kubernetes.timeout 31 | 32 | ### Comma separated list of resources file paths to load and deploy before testing. 33 | kt.env.dependencies=src/test/resources/test-secret.json 34 | -------------------------------------------------------------------------------- /src/test/resources/test-secret.json: -------------------------------------------------------------------------------- 1 | { 2 | "kind": "List", 3 | "apiVersion": "v1", 4 | "metadata": { 5 | "name": "camel-config-test", 6 | "annotations": { 7 | "description": "A test secret to be able to deploy the pod." 8 | } 9 | }, 10 | "items": [ 11 | { 12 | "kind": "Secret", 13 | "metadata": { 14 | "name": "camel-config" 15 | } 16 | } 17 | ] 18 | } --------------------------------------------------------------------------------